@zabaca/zbc 0.10.9 → 0.12.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