@zabaca/zbc 0.10.8 → 0.11.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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cloudflare-access",
3
- "description": "A Zero Trust application, its policy, and the service token a machine caller presents — the gate that lands with the tunnel it guards",
3
+ "description": "A Zero Trust application and the principals that may reach it — people by address on an allow policy, machines by service token on a Service Auth policy, each compared against its own idea of a match",
4
4
  "files": [
5
5
  {
6
6
  "path": "index.ts"
@@ -10,5 +10,5 @@
10
10
  "zod": "^3.24.0"
11
11
  },
12
12
  "secrets": [],
13
- "instructions": "Reads the Cloudflare API through `../cloudflare-api`; needs an API token with Access: Apps and Policies write on the account. Declare it beside the tunnel that exposes the hostname: a hostname on the internet with no policy in front of it is an open door, which is the failure this module exists to make hard to reach. The service token's secret is an output — put it somewhere a caller can read it, not in the declaration. In COPY mode run `zbc add cloudflare-api` too."
13
+ "instructions": "Reads the Cloudflare API through `../cloudflare-api`; needs a token with Access: Apps and Policies write on the account, plus Access: Service Tokens write if `serviceTokenName` is declared and Access: Organizations / Identity Providers for the organisation-level fields. Declare it beside the tunnel that exposes the hostname: a hostname on the internet with no policy in front of it is an open door, which is the failure this module exists to make hard to reach. THREE FIELDS ARE ORGANISATION-LEVEL, not per-application — `teamDomain`, `orgName` and `identityProviders` converge the Zero Trust organisation shared by every Access application in the account; undeclared identity providers are reported and never removed, and declaring none converges none. `emails: []` plus `serviceTokenName` is the machine-only shape (say `sessionDuration: '0s'`, so no cookie is ever issued); `emails: [...]` plus `identityProviders: ['onetimepin']` is the human shape. A minted service token's secret is returned exactly once, on the apply that creates it — put it somewhere a caller can read it, not in the declaration. In COPY mode run `zbc add cloudflare-api` too."
14
14
  }
@@ -14,6 +14,22 @@
14
14
 
15
15
  export const API = 'https://api.cloudflare.com/client/v4'
16
16
 
17
+ /**
18
+ * One entry of the envelope's `errors` array.
19
+ *
20
+ * EVERY FIELD IS OPTIONAL, and that is the point. Cloudflare does not send one
21
+ * shape: the documented one is `{code, message}`, and the Access endpoints
22
+ * answer `{code, error}`. Typing this as `{message: string}` — which it was
23
+ * until 2026-08-23 — is a claim about the API that the API does not honour, and
24
+ * it reads as true because the field is simply absent rather than wrong.
25
+ */
26
+ export interface CfApiError {
27
+ code?: number | string
28
+ message?: string
29
+ error?: string
30
+ [field: string]: unknown
31
+ }
32
+
17
33
  /**
18
34
  * Cloudflare answers every call with this envelope, including failures — the
19
35
  * HTTP status is frequently 200 on an error, so `success` is the only field
@@ -21,11 +37,57 @@ export const API = 'https://api.cloudflare.com/client/v4'
21
37
  */
22
38
  export interface CfEnvelope<T> {
23
39
  success: boolean
24
- errors: Array<{ message: string }>
40
+ errors: CfApiError[]
25
41
  result: T
26
42
  result_info?: { page: number; total_pages: number }
27
43
  }
28
44
 
45
+ /** A field that is a non-empty string once trimmed, or nothing. */
46
+ function nonEmpty(value: unknown): string | undefined {
47
+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined
48
+ }
49
+
50
+ /** One error entry as text, using whatever fields it actually carries. */
51
+ function describeCfError(entry: unknown): string {
52
+ if (entry === null || entry === undefined) return ''
53
+ if (typeof entry !== 'object') return String(entry)
54
+ const fields = entry as CfApiError
55
+ const code =
56
+ typeof fields.code === 'number' || typeof fields.code === 'string'
57
+ ? String(fields.code)
58
+ : undefined
59
+ const text = nonEmpty(fields.message) ?? nonEmpty(fields.error) ?? nonEmpty(fields.detail)
60
+ if (text !== undefined) return code === undefined ? text : `${code}: ${text}`
61
+ if (code !== undefined) {
62
+ const { code: _code, ...rest } = fields
63
+ const extra = JSON.stringify(rest)
64
+ return extra === '{}' ? code : `${code}: ${extra}`
65
+ }
66
+ const all = JSON.stringify(fields)
67
+ return all === '{}' ? '' : all
68
+ }
69
+
70
+ /**
71
+ * Everything Cloudflare said about a failure, whichever shape it said it in.
72
+ *
73
+ * ⚠️ THE ACCESS ENDPOINTS ARE THE ONES THAT ANSWER IN THE UNDOCUMENTED SHAPE.
74
+ * On 2026-08-15 `POST /accounts/{id}/access/apps` returned
75
+ * `[{"code":1010,"error":"auth.forbidden"}]`. The line here read `e.message`
76
+ * only, so it mapped to `[undefined]`, joined to the empty string, fell through
77
+ * `||` to a bare `HTTP 403`, and the one fact in the response was thrown away.
78
+ * Recovering `1010 auth.forbidden` took three throwaway diagnostic scripts, and
79
+ * it was the whole answer: a token minted with zone-scoped grants.
80
+ *
81
+ * Pure; exported for tests, and exported because a module that has to describe
82
+ * a failure Cloudflare reported outside `cf` — a batch call, a probe — must not
83
+ * grow its own copy. That copying is what this file was extracted to end.
84
+ */
85
+ export function describeCfErrors(errors: unknown, status: number): string {
86
+ const entries = Array.isArray(errors) ? errors : []
87
+ const parts = entries.map(describeCfError).filter((part) => part !== '')
88
+ return parts.length > 0 ? parts.join('; ') : `HTTP ${status}`
89
+ }
90
+
29
91
  /**
30
92
  * Call the API and return the WHOLE envelope; throw the API's own message on
31
93
  * failure. Callers that paginate need `result_info`, which is why this exists
@@ -44,8 +106,9 @@ export async function cfRaw<T>(
44
106
  })
45
107
  const payload = (await res.json()) as CfEnvelope<T>
46
108
  if (!payload.success) {
47
- const messages = payload.errors?.map((e) => e.message).join('; ') || `HTTP ${res.status}`
48
- throw new Error(`Cloudflare API ${method} ${path} failed: ${messages}`)
109
+ throw new Error(
110
+ `Cloudflare API ${method} ${path} failed: ${describeCfErrors(payload.errors, res.status)}`,
111
+ )
49
112
  }
50
113
  return payload
51
114
  }
@@ -76,16 +139,41 @@ export function resolveApiToken(
76
139
  ref: { from: string; output: string },
77
140
  imports: Record<string, unknown>,
78
141
  ): string {
142
+ return resolveRef(ref, imports, 'apiToken')
143
+ }
144
+
145
+ /**
146
+ * The same resolution, for a reference that is NOT the API token.
147
+ *
148
+ * `apiToken` was the only `{from, output}` a Cloudflare module took until
149
+ * `cloudflare-access` grew a list of service-token references. The field name
150
+ * is a parameter because the error message is the whole value of this function:
151
+ * one that says `apiToken` for the third entry of `serviceTokens` sends the
152
+ * reader to the wrong line of an instance file.
153
+ *
154
+ * The parameter is typed loosely on purpose. A zod-inferred config marks both
155
+ * halves optional in some spellings, and the checks have to run at runtime
156
+ * regardless — a `from` naming an instance that is not imported is a real
157
+ * failure mode and nothing in the type system is catching it here.
158
+ */
159
+ export function resolveRef(
160
+ ref: { from?: string; output?: string },
161
+ imports: Record<string, unknown>,
162
+ field: string,
163
+ ): string {
164
+ if (!ref.from || !ref.output) {
165
+ throw new Error(`${field} must name both an instance (\`from\`) and an output (\`output\`)`)
166
+ }
79
167
  const outputs = imports[ref.from]
80
168
  if (outputs === undefined) {
81
169
  throw new Error(
82
- `apiToken references instance "${ref.from}", which is not in this instance's imports`,
170
+ `${field} references instance "${ref.from}", which is not in this instance's imports`,
83
171
  )
84
172
  }
85
173
  const value = (outputs as Record<string, unknown> | null)?.[ref.output]
86
174
  if (typeof value !== 'string' || value === '') {
87
175
  throw new Error(
88
- `apiToken references output "${ref.output}" on instance "${ref.from}", which doesn't emit it`,
176
+ `${field} references output "${ref.output}" on instance "${ref.from}", which doesn't emit it`,
89
177
  )
90
178
  }
91
179
  return value
@@ -220,6 +220,62 @@ async function ensureDestinationVerified(
220
220
  )
221
221
  }
222
222
 
223
+ /** Recorded in outputs when the API carried no status for a record. */
224
+ const UNREPORTED = 'unreported'
225
+
226
+ /** One record as the Sending API returned it, plus how it should be labelled. */
227
+ export interface SendingDnsReading {
228
+ /** `MX cf-bounce.example.com` — what a warning prints. */
229
+ key: string
230
+ /** The status Cloudflare reported, or `null` when it reported none. */
231
+ status: string | null
232
+ }
233
+
234
+ /**
235
+ * Read one Sending DNS record.
236
+ *
237
+ * The API is beta and its field names have moved, so this reads defensively —
238
+ * but the defensiveness stops at the LABEL. `type` and `name` fall back to
239
+ * placeholders because a wrong guess there only mislabels a line. `status` does
240
+ * not fall back at all: it returns `null` when the API carried none, because the
241
+ * previous `?? 'unknown'` produced a string the caller then compared against
242
+ * active|verified|locked, failed, and printed as `Sending DNS pending`.
243
+ *
244
+ * That turned "I could not find the field" into a claim about the customer's
245
+ * DNS. On one zone it fired on all four records — MX, SPF, DKIM, DMARC — every
246
+ * apply, while every record resolved correctly and the domain published
247
+ * `p=reject`, under which unaligned mail is refused rather than delivered. Mail
248
+ * was flowing the whole time. Absence and failure are different answers and only
249
+ * one of them is about DNS.
250
+ */
251
+ export function readSendingDnsRecord(
252
+ record: Record<string, unknown>,
253
+ domain: string,
254
+ ): SendingDnsReading {
255
+ const reported = record.status ?? record.state
256
+ return {
257
+ key: `${String(record.type ?? 'record')} ${String(record.name ?? domain)}`,
258
+ status: reported === undefined || reported === null ? null : String(reported),
259
+ }
260
+ }
261
+
262
+ /** A status Cloudflare reports for a record that is live and serving. */
263
+ const LIVE = new Set(['active', 'verified', 'locked'])
264
+
265
+ export interface SendingDnsVerdict {
266
+ /** Reported as something other than live. A real warning. */
267
+ pending: SendingDnsReading[]
268
+ /** Carried no status. The module's blind spot, not a fact about the zone. */
269
+ unreported: SendingDnsReading[]
270
+ }
271
+
272
+ export function classifySendingDns(readings: SendingDnsReading[]): SendingDnsVerdict {
273
+ return {
274
+ pending: readings.filter((r) => r.status !== null && !LIVE.has(r.status)),
275
+ unreported: readings.filter((r) => r.status === null),
276
+ }
277
+ }
278
+
223
279
  export const cloudflareEmailModule = defineModule({
224
280
  name: 'cloudflare-email',
225
281
  configSchema: z.object({
@@ -286,13 +342,18 @@ export const cloudflareEmailModule = defineModule({
286
342
  ? (dns as Array<Record<string, unknown>>)
287
343
  : (((dns as Record<string, unknown>)?.['records'] as Array<Record<string, unknown>>) ??
288
344
  [])
289
- for (const r of records) {
290
- const key = `${String(r.type ?? 'record')} ${String(r.name ?? domain)}`
291
- const status = String(r.status ?? r.state ?? 'unknown')
292
- dnsStatus[key] = status
293
- if (status !== 'active' && status !== 'verified' && status !== 'locked') {
294
- console.log(` ⚠ Sending DNS pending: ${key} → ${status}`)
295
- }
345
+ const readings = records.map((r) => readSendingDnsRecord(r, domain))
346
+ const verdict = classifySendingDns(readings)
347
+ for (const r of readings) dnsStatus[r.key] = r.status ?? UNREPORTED
348
+ for (const r of verdict.pending) {
349
+ console.log(` ⚠ Sending DNS pending: ${r.key} → ${r.status}`)
350
+ }
351
+ if (verdict.unreported.length > 0) {
352
+ // Said once, and not as a warning: the records may be perfectly fine.
353
+ console.log(
354
+ ` Sending DNS: the API reported no status for ${verdict.unreported.length} record(s) ` +
355
+ `— not a claim about the zone; check them with dig if in doubt`,
356
+ )
296
357
  }
297
358
  } catch (err) {
298
359
  console.log(` ⚠ Could not read sending DNS status: ${(err as Error).message}`)
@@ -421,7 +482,7 @@ export const cloudflareEmailModule = defineModule({
421
482
  }
422
483
 
423
484
  const pending = Object.entries(dnsStatus).filter(
424
- ([, s]) => s !== 'active' && s !== 'verified' && s !== 'locked',
485
+ ([, s]) => s !== UNREPORTED && s !== 'active' && s !== 'verified' && s !== 'locked',
425
486
  )
426
487
  if (pending.length > 0) {
427
488
  console.log(