@jini-ai/devops 0.5.4 → 0.5.6

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 (62) hide show
  1. package/CHANGELOG.md +10 -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 +33 -26
  52. package/dist/packaging/electron/imports.d.ts +2 -2
  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/contracts.d.ts +9 -0
  58. package/dist/static-export/node-adapters.js +26 -17
  59. package/dist/static-export/runner.js +202 -65
  60. package/dist/static-export/transforms.d.ts +8 -1
  61. package/dist/static-export/transforms.js +44 -23
  62. package/package.json +23 -6
@@ -38,41 +38,79 @@ export function normalizeDeploymentUrl({ url }) {
38
38
  return '';
39
39
  return /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;
40
40
  }
41
+ /**
42
+ * Folds a guard refusal, transport error, abort or body-read failure into the
43
+ * single unreachable shape. Keep unknown throw values readable: host guards and
44
+ * transports may throw values other than Error.
45
+ * @complexity O(1).
46
+ */
47
+ function unreachableCheck({ err }) {
48
+ return {
49
+ reachable: false,
50
+ statusMessage: `Public link is not reachable yet: ${err instanceof Error ? err.message : String(err)}`,
51
+ };
52
+ }
53
+ /**
54
+ * Starts the per-probe deadline: rejects `timeout` and then aborts `signal`
55
+ * once `timeoutMs` elapses. `clear` must run on every exit.
56
+ * @complexity O(1).
57
+ */
58
+ function startProbeDeadline({ timeoutMs }) {
59
+ const controller = new AbortController();
60
+ let timer;
61
+ // Race the transport as well as signalling it: an injected fetch/body reader may ignore abort.
62
+ const timeout = new Promise((_resolve, reject) => {
63
+ timer = setTimeout(() => {
64
+ reject(new Error(`probe timed out after ${timeoutMs}ms`));
65
+ controller.abort();
66
+ }, timeoutMs);
67
+ });
68
+ return { signal: controller.signal, timeout, clear: () => clearTimeout(timer) };
69
+ }
70
+ /**
71
+ * Classifies one probe response as reachable / protected / unreachable. A 401
72
+ * body (and any GET body) is read under the same `timeout` race as the request.
73
+ * @complexity O(body size) for the read; O(1) otherwise.
74
+ */
75
+ async function classifyProbeResponse({ resp, method, timeout }, options) {
76
+ if (resp.status >= 200 && resp.status < 400)
77
+ return { reachable: true, statusCode: resp.status };
78
+ const body = method === 'GET' || resp.status === 401 ? await Promise.race([resp.text(), timeout]) : '';
79
+ if (resp.status === 401 && options.detectProtected?.({ resp, body })) {
80
+ return {
81
+ reachable: false,
82
+ status: 'protected',
83
+ statusCode: resp.status,
84
+ statusMessage: options.protectedMessage ?? 'Deployment is protected by the provider.',
85
+ };
86
+ }
87
+ return {
88
+ reachable: false,
89
+ statusCode: resp.status,
90
+ statusMessage: `Public link returned HTTP ${resp.status}.`,
91
+ };
92
+ }
41
93
  /**
42
94
  * Issues a single HEAD/GET probe against a deployment URL with a bounded
43
95
  * timeout, classifying the outcome as reachable / protected / unreachable.
44
96
  *
45
- * @param url - Absolute URL to probe.
46
- * @param method - HTTP method for this probe.
47
- * @param timeoutMs - Abort the request after this many milliseconds.
97
+ * @param requiredArgs - Absolute URL, HTTP method, budget in ms, and the paired fetch and guard ports.
48
98
  * @param options - Optional protected-response detector + message.
49
99
  * @returns A `DeploymentUrlCheck` describing the outcome. Never throws —
50
100
  * network errors and aborts are folded into `{ reachable: false, statusMessage }`.
51
101
  * @complexity O(1) network round-trip.
52
102
  * @overallScore 100/100
53
103
  */
54
- async function requestDeploymentUrl(url, method, timeoutMs, options, fetchPort, guard) {
104
+ async function requestDeploymentUrl({ url, method, timeoutMs, fetch: fetchPort, guard }, options) {
55
105
  let safeUrl;
56
106
  try {
57
107
  safeUrl = assertSafeDeploymentUrl(url, guard);
58
108
  }
59
109
  catch (err) {
60
- // Keep unknown throw values readable: host guards may throw values other than Error.
61
110
  // The old concrete guard only threw AssetCacheError, but ports cannot assume that contract.
62
- return {
63
- reachable: false,
64
- statusMessage: `Public link is not reachable yet: ${err instanceof Error ? err.message : String(err)}`,
65
- };
111
+ return unreachableCheck({ err });
66
112
  }
67
- const controller = new AbortController();
68
- let timer;
69
- // Race the transport as well as signalling it: an injected fetch/body reader may ignore abort.
70
- const timeout = new Promise((_resolve, reject) => {
71
- timer = setTimeout(() => {
72
- reject(new Error(`probe timed out after ${timeoutMs}ms`));
73
- controller.abort();
74
- }, timeoutMs);
75
- });
113
+ const deadline = startProbeDeadline({ timeoutMs });
76
114
  // Real refactor, not a padded test: this used to be `try { ... } catch {
77
115
  // ... } finally { clearTimeout(timer); }`. A throwaway local repro (see
78
116
  // the archived extraction source map's 2026-07-22 addition) proved that V8's own
@@ -90,35 +128,15 @@ async function requestDeploymentUrl(url, method, timeoutMs, options, fetchPort,
90
128
  try {
91
129
  // The injected transport owns DNS pinning (the Node adapter attaches its validating dispatcher).
92
130
  // A separate preflight resolver would leave the validation/connect TOCTOU gap open.
93
- const init = { method, redirect: 'manual', signal: controller.signal };
94
- const resp = await Promise.race([fetchPort({ url: safeUrl.toString() }, { init }), timeout]);
95
- if (resp.status >= 200 && resp.status < 400) {
96
- clearTimeout(timer);
97
- return { reachable: true, statusCode: resp.status };
98
- }
99
- const body = method === 'GET' || resp.status === 401 ? await Promise.race([resp.text(), timeout]) : '';
100
- if (resp.status === 401 && options.detectProtected?.({ resp, body })) {
101
- clearTimeout(timer);
102
- return {
103
- reachable: false,
104
- status: 'protected',
105
- statusCode: resp.status,
106
- statusMessage: options.protectedMessage ?? 'Deployment is protected by the provider.',
107
- };
108
- }
109
- clearTimeout(timer);
110
- return {
111
- reachable: false,
112
- statusCode: resp.status,
113
- statusMessage: `Public link returned HTTP ${resp.status}.`,
114
- };
131
+ const init = { method, redirect: 'manual', signal: deadline.signal };
132
+ const resp = await Promise.race([fetchPort({ url: safeUrl.toString() }, { init }), deadline.timeout]);
133
+ const check = await classifyProbeResponse({ resp, method, timeout: deadline.timeout }, options);
134
+ deadline.clear();
135
+ return check;
115
136
  }
116
137
  catch (err) {
117
- clearTimeout(timer);
118
- return {
119
- reachable: false,
120
- statusMessage: `Public link is not reachable yet: ${err instanceof Error ? err.message : String(err)}`,
121
- };
138
+ deadline.clear();
139
+ return unreachableCheck({ err });
122
140
  }
123
141
  }
124
142
  /**
@@ -139,46 +157,90 @@ export async function checkDeploymentUrl({ url, fetch: fetchPort, guard }, optio
139
157
  }
140
158
  const timeoutMs = options.timeoutMs ?? 8_000;
141
159
  const deadlineAt = Date.now() + timeoutMs;
142
- const head = await requestDeploymentUrl(normalized, 'HEAD', timeoutMs, options, fetchPort, guard);
143
- if (head.reachable)
144
- return head;
145
- if (head.status === 'protected')
160
+ const probe = { url: normalized, fetch: fetchPort, guard };
161
+ const head = await requestDeploymentUrl({ ...probe, method: 'HEAD', timeoutMs }, options);
162
+ if (head.reachable || head.status === 'protected')
146
163
  return head;
147
164
  // HEAD and its fallback share one probe budget; do not restart the clock for GET.
148
165
  const remainingMs = deadlineAt - Date.now();
149
166
  if (remainingMs <= 0)
150
167
  return head;
151
- if (head.statusCode && (head.statusCode === 405 || head.statusCode === 403 || head.statusCode >= 400)) {
152
- const get = await requestDeploymentUrl(normalized, 'GET', remainingMs, options, fetchPort, guard);
153
- if (get.reachable)
154
- return get;
155
- if (get.status === 'protected')
156
- return get;
157
- // Real refactor, not a padded test: this used to be `get.statusMessage ?
158
- // get : head`, but `get.statusMessage` is unconditionally truthy by the
159
- // time control reaches here. `requestDeploymentUrl` has exactly 3 return
160
- // shapes with `reachable: false`: the `assertSafeDeploymentUrl` catch
161
- // (statusMessage is a non-empty template string), the generic non-2xx/3xx
162
- // fallback (`Public link returned HTTP ${status}.`, always non-empty),
163
- // and the outer catch (same non-empty template as the first case). The
164
- // remaining `reachable: false` shape (`status: 'protected'`) is already
165
- // excluded by the `get.status === 'protected'` check just above. So the
166
- // `: head` fallback branch could never actually be selected — see
167
- // the archived extraction source map's 2026-07-22 addition for the exhaustive
168
- // case-by-case proof this was re-derived from.
169
- return get;
168
+ // Every non-reachable, non-protected HEAD falls back to GET. This used to be two
169
+ // arms — `if (head.statusCode && (405 || 403 || >= 400)) { GET ... } else { GET ... }` —
170
+ // that issued the identical GET with identical arguments and both returned it, so
171
+ // the condition selected between two identical actions and was merged away.
172
+ //
173
+ // Real refactor, not a padded test: the first arm used to end in `get.statusMessage ?
174
+ // get : head`, but `get.statusMessage` is unconditionally truthy by the
175
+ // time control reaches there. `requestDeploymentUrl` has exactly 3 return
176
+ // shapes with `reachable: false`: the `assertSafeDeploymentUrl` catch
177
+ // (statusMessage is a non-empty template string), the generic non-2xx/3xx
178
+ // fallback (`Public link returned HTTP ${status}.`, always non-empty),
179
+ // and the outer catch (same non-empty template as the first case). The
180
+ // remaining `reachable: false` shape (`status: 'protected'`) is already
181
+ // excluded by a `get.status === 'protected'` check that preceded it. So the
182
+ // `: head` fallback branch could never actually be selected — see
183
+ // the archived extraction source map's 2026-07-22 addition for the exhaustive
184
+ // case-by-case proof this was re-derived from.
185
+ // Same reasoning for the second arm, plus: when `get.reachable` is true, `get` is
186
+ // returned directly regardless (matching the removed ternary's consequent) — so the
187
+ // whole expression always evaluated to `get`, for every `get` shape
188
+ // `requestDeploymentUrl` can produce.
189
+ return requestDeploymentUrl({ ...probe, method: 'GET', timeoutMs: remainingMs }, options);
190
+ }
191
+ /** Milliseconds left in the overall polling budget, read from the injected clock. @complexity O(1). */
192
+ function remainingBudget(ctx) {
193
+ return ctx.timeoutMs - (ctx.now({}) - ctx.startedAt);
194
+ }
195
+ /**
196
+ * Probes every candidate once, in order, within the remaining budget.
197
+ * Returns `done` for a ready candidate, or for the first protected candidate once
198
+ * the others had their turn; otherwise the latest failure message (or the
199
+ * caller's previous one when no candidate was probed).
200
+ * @complexity O(candidates) probes.
201
+ */
202
+ async function sweepCandidates(ctx, { lastMessage }) {
203
+ let protectedResult;
204
+ for (const url of ctx.candidates) {
205
+ const remainingMs = remainingBudget(ctx);
206
+ if (remainingMs <= 0)
207
+ break;
208
+ const probeTimeoutMs = Math.min(ctx.options.timeoutMs ?? 8_000, remainingMs);
209
+ const result = await checkDeploymentUrl({ url, fetch: ctx.fetch, guard: ctx.guard }, { ...ctx.options, timeoutMs: probeTimeoutMs });
210
+ if (result.reachable) {
211
+ return { done: { status: 'ready', url, statusMessage: 'Public link is ready.', reachableAt: ctx.now({}) } };
212
+ }
213
+ if (result.status === 'protected') {
214
+ protectedResult ??= {
215
+ status: 'protected',
216
+ url,
217
+ statusMessage: result.statusMessage || `${ctx.providerLabel} is gating this link behind its own auth wall.`,
218
+ };
219
+ continue;
220
+ }
221
+ // Real refactor, not a padded test: `result.statusMessage` is
222
+ // unconditionally truthy by this point. `result` comes from
223
+ // `checkDeploymentUrl`, which — for every `reachable: false`,
224
+ // non-`'protected'` shape it can produce (the empty-URL guard, and
225
+ // both `requestDeploymentUrl`-derived returns after the dead-branch
226
+ // refactor just above) — always sets a non-empty `statusMessage`. The
227
+ // `reachable: true` and `status === 'protected'` shapes are both
228
+ // handled by the `return` and `continue` above this line, so neither
229
+ // can reach here. `|| lastMessage` (falling back to the *previous*
230
+ // sweep's message) could therefore never actually be selected — see
231
+ // the archived extraction source map's 2026-07-22 addition for the proof.
232
+ // Non-null assertion (not `||`/`??`, which would just reintroduce the
233
+ // same dead branch): the type is `string | undefined` because
234
+ // `DeploymentUrlCheck.statusMessage` is optional in general, but this
235
+ // exact call site's result is always defined per the proof above.
236
+ lastMessage = result.statusMessage;
170
237
  }
171
- const get = await requestDeploymentUrl(normalized, 'GET', remainingMs, options, fetchPort, guard);
172
- // Same reasoning as the `get.statusMessage ? get : head` case just above,
173
- // plus: when `get.reachable` is true, `get` is returned directly regardless
174
- // (matching the removed ternary's consequent) — so this whole expression
175
- // always evaluates to `get`, for every `get` shape `requestDeploymentUrl`
176
- // can produce.
177
- return get;
238
+ // A protected candidate is a fallback only after the other candidates had their turn.
239
+ return protectedResult ? { done: protectedResult } : { lastMessage };
178
240
  }
179
241
  /**
180
- * Polls a set of deployment URL candidates until one becomes reachable, one
181
- * reports as provider-protected, or `timeoutMs` elapses. Used right after a
242
+ * Polls deployment candidates until one becomes reachable or `timeoutMs` elapses.
243
+ * A protected result is returned after its sweep if no candidate is ready. Used right after a
182
244
  * publish call returns, since providers frequently accept the deploy before
183
245
  * the URL is actually resolvable.
184
246
  *
@@ -193,51 +255,35 @@ export async function checkDeploymentUrl({ url, fetch: fetchPort, guard }, optio
193
255
  */
194
256
  export async function waitForReachableDeploymentUrl({ urls, fetch: fetchPort, guard, now, sleep }, options = {}) {
195
257
  const { timeoutMs = 60_000, intervalMs = 2_000, providerLabel = 'Deployment provider' } = options;
196
- const candidates = [...new Set((urls || []).map((url) => normalizeDeploymentUrl({ url })).filter(Boolean))];
197
- const fallbackUrl = candidates[0] || '';
198
- if (!fallbackUrl) {
258
+ const candidates = uniqueCandidates({ urls });
259
+ if (candidates.length === 0) {
199
260
  return {
200
261
  status: 'link-delayed',
201
262
  url: '',
202
263
  statusMessage: `${providerLabel} did not return a public deployment URL.`,
203
264
  };
204
265
  }
205
- const startedAt = now({});
266
+ const ctx = { candidates, fetch: fetchPort, guard, now, startedAt: now({}), timeoutMs, providerLabel, options };
267
+ return pollCandidates(ctx, { sleep, intervalMs });
268
+ }
269
+ /** Normalized, de-duplicated, non-empty candidates in first-seen order. A null/undefined
270
+ * `urls` from an untyped caller is treated as empty. @complexity O(urls). */
271
+ function uniqueCandidates({ urls }) {
272
+ return [...new Set((urls || []).map((url) => normalizeDeploymentUrl({ url })).filter(Boolean))];
273
+ }
274
+ /**
275
+ * Sweeps, then sleeps `min(intervalMs, remaining)`, until a sweep is done or the budget
276
+ * (or a stalled sleep) runs out; then reports `link-delayed` against the first candidate.
277
+ * @complexity O(candidates * timeoutMs/intervalMs) probes.
278
+ */
279
+ async function pollCandidates(ctx, { sleep, intervalMs }) {
206
280
  let lastMessage = '';
207
- while (now({}) - startedAt < timeoutMs) {
208
- for (const url of candidates) {
209
- const remainingMs = timeoutMs - (now({}) - startedAt);
210
- if (remainingMs <= 0)
211
- break;
212
- const result = await checkDeploymentUrl({ url, fetch: fetchPort, guard }, { ...options, timeoutMs: Math.min(options.timeoutMs ?? 8_000, remainingMs) });
213
- if (result.reachable) {
214
- return { status: 'ready', url, statusMessage: 'Public link is ready.', reachableAt: now({}) };
215
- }
216
- if (result.status === 'protected') {
217
- return {
218
- status: 'protected',
219
- url,
220
- statusMessage: result.statusMessage || `${providerLabel} is gating this link behind its own auth wall.`,
221
- };
222
- }
223
- // Real refactor, not a padded test: `result.statusMessage` is
224
- // unconditionally truthy by this point. `result` comes from
225
- // `checkDeploymentUrl`, which — for every `reachable: false`,
226
- // non-`'protected'` shape it can produce (the empty-URL guard, and
227
- // both `requestDeploymentUrl`-derived returns after the dead-branch
228
- // refactor just above) — always sets a non-empty `statusMessage`. The
229
- // `reachable: true` and `status === 'protected'` shapes are both
230
- // handled by the two `return`s directly above this line, so neither
231
- // can reach here. `|| lastMessage` (falling back to the *previous*
232
- // sweep's message) could therefore never actually be selected — see
233
- // the archived extraction source map's 2026-07-22 addition for the proof.
234
- // Non-null assertion (not `||`/`??`, which would just reintroduce the
235
- // same dead branch): the type is `string | undefined` because
236
- // `DeploymentUrlCheck.statusMessage` is optional in general, but this
237
- // exact call site's result is always defined per the proof above.
238
- lastMessage = result.statusMessage;
239
- }
240
- const remainingMs = timeoutMs - (now({}) - startedAt);
281
+ while (remainingBudget(ctx) > 0) {
282
+ const sweep = await sweepCandidates(ctx, { lastMessage });
283
+ if ('done' in sweep)
284
+ return sweep.done;
285
+ lastMessage = sweep.lastMessage;
286
+ const remainingMs = remainingBudget(ctx);
241
287
  if (remainingMs <= 0)
242
288
  break;
243
289
  if (!await sleepWithinBudget({ sleep, ms: Math.min(intervalMs, remainingMs), timeoutMs: remainingMs }))
@@ -245,8 +291,9 @@ export async function waitForReachableDeploymentUrl({ urls, fetch: fetchPort, gu
245
291
  }
246
292
  return {
247
293
  status: 'link-delayed',
248
- url: fallbackUrl,
249
- statusMessage: lastMessage || `${providerLabel} returned a deployment URL, but it is not reachable yet.`,
294
+ // Non-empty: waitForReachableDeploymentUrl returns early when no candidate survives.
295
+ url: ctx.candidates[0],
296
+ statusMessage: lastMessage || `${ctx.providerLabel} returned a deployment URL, but it is not reachable yet.`,
250
297
  };
251
298
  }
252
299
  /** An injected delay can stall too; its completion cannot extend the whole polling deadline.
@@ -0,0 +1,61 @@
1
+ /**
2
+ * @file Approval BINDING for DNS change plans (the apply engine is D4). Lifted from a host deploy
3
+ * plugin's fingerprinted, re-previewed approval and made generic: an approval is bound to
4
+ * the exact plan (fingerprint), the workspace, the provider account and the authoritative zone,
5
+ * and it expires. Before anything is applied the plan is recomputed and checked again here.
6
+ *
7
+ * Deletes are for humans only; anything touching the apex or MX is never "remembered" as a
8
+ * standing approval, because a wrong apex or mail record takes the whole domain down.
9
+ */
10
+ import type { DnsChangePlan } from './contract.js';
11
+ export type DnsApprover = 'human' | 'agent';
12
+ export interface DnsApproval {
13
+ readonly fingerprint: string;
14
+ readonly workspaceId: string;
15
+ readonly providerAccountId: string;
16
+ readonly zone: string;
17
+ readonly expiresAt: number;
18
+ /** True when any change touches the apex or MX, or deletes: approve each time, never remember. */
19
+ readonly nonRememberable: boolean;
20
+ /** True when any change deletes: only a human approval counts. */
21
+ readonly humanOnly: boolean;
22
+ readonly approvedBy: DnsApprover;
23
+ }
24
+ export type DnsApprovalRefusal = 'wrong_binding' | 'expired' | 'inventory_incomplete' | 'blocked' | 'stale_fingerprint' | 'human_required' | 'not_rememberable';
25
+ export type DnsApprovalCheck = {
26
+ readonly ok: true;
27
+ } | {
28
+ readonly ok: false;
29
+ readonly reason: DnsApprovalRefusal;
30
+ readonly message: string;
31
+ };
32
+ /**
33
+ * Bind an approval to one plan. `approvedBy` defaults to `agent` so an approval of unknown origin
34
+ * fails closed on human-only plans.
35
+ */
36
+ export declare function bindDnsApproval(required: {
37
+ readonly plan: DnsChangePlan;
38
+ readonly workspaceId: string;
39
+ readonly providerAccountId: string;
40
+ readonly zone: string;
41
+ readonly ttlMs: number;
42
+ readonly now: number;
43
+ }, optional?: {
44
+ readonly approvedBy?: DnsApprover;
45
+ }): DnsApproval;
46
+ /**
47
+ * Re-check an approval against a plan recomputed just now. The fingerprint is recomputed from the
48
+ * fresh plan's content rather than trusted from its field.
49
+ * @param optional.remembered - The approval is a standing ("remember this") approval being reused.
50
+ */
51
+ export declare function checkDnsApproval(required: {
52
+ readonly approval: DnsApproval;
53
+ readonly freshPlan: DnsChangePlan;
54
+ readonly workspaceId: string;
55
+ readonly providerAccountId: string;
56
+ readonly zone: string;
57
+ readonly now: number;
58
+ }, optional?: {
59
+ readonly remembered?: boolean;
60
+ }): DnsApprovalCheck;
61
+ //# sourceMappingURL=approval.d.ts.map
@@ -0,0 +1,48 @@
1
+ import { fingerprintPlan } from './plan.js';
2
+ import { normalizeDnsName } from './records.js';
3
+ function changeName(change) {
4
+ return (change.after ?? change.before)?.name ?? '';
5
+ }
6
+ function touchesApexOrMail(change, zone) {
7
+ const types = [change.before?.type, change.after?.type];
8
+ return types.includes('MX') || normalizeDnsName({ name: changeName(change) }) === zone;
9
+ }
10
+ /**
11
+ * Bind an approval to one plan. `approvedBy` defaults to `agent` so an approval of unknown origin
12
+ * fails closed on human-only plans.
13
+ */
14
+ export function bindDnsApproval(required, optional = {}) {
15
+ const zone = normalizeDnsName({ name: required.zone });
16
+ const humanOnly = required.plan.changes.some(change => change.op === 'delete');
17
+ return {
18
+ fingerprint: required.plan.fingerprint,
19
+ workspaceId: required.workspaceId,
20
+ providerAccountId: required.providerAccountId,
21
+ zone,
22
+ expiresAt: required.now + required.ttlMs,
23
+ nonRememberable: humanOnly || required.plan.changes.some(change => touchesApexOrMail(change, zone)),
24
+ humanOnly,
25
+ approvedBy: optional.approvedBy ?? 'agent',
26
+ };
27
+ }
28
+ /** Ordered checks; the first failing one is the refusal. */
29
+ const CHECKS = [
30
+ ['wrong_binding', input => input.approval.workspaceId !== input.workspaceId || input.approval.providerAccountId !== input.providerAccountId || input.approval.zone !== normalizeDnsName({ name: input.zone }) || input.freshPlan.zone !== input.approval.zone, 'The approval was given for a different workspace, provider account or zone.'],
31
+ ['expired', input => input.now >= input.approval.expiresAt, 'The approval has expired; review the plan again.'],
32
+ ['inventory_incomplete', input => input.freshPlan.inventory !== 'complete', 'The existing records could not be fully read, so nothing may be changed.'],
33
+ ['blocked', input => input.freshPlan.blockers.length > 0, 'The current plan has blockers.'],
34
+ ['stale_fingerprint', input => fingerprintPlan({ plan: input.freshPlan }) !== input.approval.fingerprint, 'The DNS records changed since the plan was approved; review the new plan.'],
35
+ ['human_required', input => input.approval.humanOnly && input.approval.approvedBy !== 'human', 'The plan deletes records, which only a person may approve.'],
36
+ ['not_rememberable', input => input.remembered && input.approval.nonRememberable, 'Changes to the apex, mail or deletions need a fresh approval every time.'],
37
+ ];
38
+ /**
39
+ * Re-check an approval against a plan recomputed just now. The fingerprint is recomputed from the
40
+ * fresh plan's content rather than trusted from its field.
41
+ * @param optional.remembered - The approval is a standing ("remember this") approval being reused.
42
+ */
43
+ export function checkDnsApproval(required, optional = {}) {
44
+ const input = { ...required, remembered: optional.remembered ?? false };
45
+ const failed = CHECKS.find(([, fails]) => fails(input));
46
+ return failed ? { ok: false, reason: failed[0], message: failed[2] } : { ok: true };
47
+ }
48
+ //# sourceMappingURL=approval.js.map