@serve.zone/interfaces 32.88.0 → 32.89.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.
Files changed (40) hide show
  1. package/changelog.md +11 -0
  2. package/dist_ts/00_commitinfo_data.js +1 -1
  3. package/dist_ts/data/cloudaccess.d.ts +402 -0
  4. package/dist_ts/data/cloudaccess.js +685 -0
  5. package/dist_ts/data/cloudlyconfig.d.ts +20 -0
  6. package/dist_ts/data/cloudlyconfig.js +21 -1
  7. package/dist_ts/data/gatewayareas.d.ts +114 -19
  8. package/dist_ts/data/gatewayareas.js +36 -1
  9. package/dist_ts/data/gatewayareas.validation.js +178 -36
  10. package/dist_ts/data/gatewayconnector.d.ts +2 -2
  11. package/dist_ts/data/gatewayconnector.js +20 -1
  12. package/dist_ts/data/gatewayintent.d.ts +154 -0
  13. package/dist_ts/data/gatewayintent.js +61 -0
  14. package/dist_ts/data/index.d.ts +2 -0
  15. package/dist_ts/data/index.js +3 -1
  16. package/dist_ts/data/witness.js +4 -9
  17. package/dist_ts/private/bearerencoding.d.ts +9 -0
  18. package/dist_ts/private/bearerencoding.js +17 -0
  19. package/dist_ts/private/storagecontract.js +3 -3
  20. package/dist_ts/requests/cloudaccess.d.ts +125 -0
  21. package/dist_ts/requests/cloudaccess.js +2 -0
  22. package/dist_ts/requests/gatewayconnector.d.ts +33 -1
  23. package/dist_ts/requests/index.d.ts +2 -1
  24. package/dist_ts/requests/index.js +3 -2
  25. package/package.json +1 -1
  26. package/readme.md +146 -10
  27. package/ts/00_commitinfo_data.ts +1 -1
  28. package/ts/data/cloudaccess.ts +1133 -0
  29. package/ts/data/cloudlyconfig.ts +27 -0
  30. package/ts/data/gatewayareas.ts +82 -19
  31. package/ts/data/gatewayareas.validation.ts +192 -34
  32. package/ts/data/gatewayconnector.ts +19 -0
  33. package/ts/data/gatewayintent.ts +209 -0
  34. package/ts/data/index.ts +2 -0
  35. package/ts/data/witness.ts +3 -10
  36. package/ts/private/bearerencoding.ts +24 -0
  37. package/ts/private/storagecontract.ts +2 -2
  38. package/ts/requests/cloudaccess.ts +201 -0
  39. package/ts/requests/gatewayconnector.ts +41 -1
  40. package/ts/requests/index.ts +2 -0
@@ -0,0 +1,1133 @@
1
+ import { isCanonicalBase64url32, isSha256Hex } from '../private/bearerencoding.js';
2
+ import {
3
+ validateControllerCounter,
4
+ validateControllerIdentifier,
5
+ validateControllerNonNegativeInteger,
6
+ validateControllerOrigin,
7
+ } from '../private/controllercontract.js';
8
+ import { readDataElements, readExactDataRecord } from '../private/dataproperties.js';
9
+ import { parseCanonicalIpAddress } from '../private/ipaddress.js';
10
+ import type { TCompleteKeyList } from '../private/keylist.js';
11
+ import { controllerPeerSetContract } from './controller.js';
12
+ import { isGatewayClientHostname } from './gateway.js';
13
+ import { isLocationName } from './location.js';
14
+ import { isReleaseVersion } from './releaseversion.js';
15
+ import type { IUser } from './user.js';
16
+
17
+ /*
18
+ * Cloud access (AGL-1181, Linus ruling 141 and amendment 141a): cloudaccess.serve.zone, a directory
19
+ * of controllers with an SNI-passthrough relay. It is a directory, never an authority: it holds no
20
+ * controller credential, sends no command and terminates no customer name.
21
+ *
22
+ * A controller (Cloudly) dials one typedsocket to cloud access with WebPKI verification and sends
23
+ * `requests.cloudaccess` `Cloudly_CloudAccess` requests over it. Cloud access calls back over that
24
+ * socket with exactly one request, `openCloudAccessStream`, and nothing else: Cloudly creates the
25
+ * socket's client with a dedicated TypedRouter that registers only that handler, never its main
26
+ * router. Nothing is pushed; a condition cloud access holds about a binding reaches Cloudly as a
27
+ * named refusal of Cloudly's next call or in `getCloudAccessBindingState`.
28
+ *
29
+ * Pairing (C3). Cloudly creates a bearer (base64url of `cloudAccessContract.bearerRandomBytes`
30
+ * random bytes), keeps it in its keyring-encrypted secret store and enrolls with its SHA-256 only
31
+ * (`enrollCloudAccessBinding`). Cloud access assigns a random `bindingId` and a pairing code that
32
+ * lives on the enrolling socket: when that socket closes, or after
33
+ * `cloudAccessContract.pairingCodeLifetimeMs`, the enrollment is gone. A person who may claim enters
34
+ * the code on cloud access's own page and picks an idp.global organization, which records a pending
35
+ * claim; Cloudly's Settings polls `getCloudAccessEnrollmentState`, and only its Administrator's
36
+ * `confirmCloudAccessEnrollment` activates the binding. Afterwards Cloudly authenticates every
37
+ * socket with the bearer (`authenticateCloudAccessBinding`), registers it
38
+ * (`registerCloudAccessSession`), reports every `cloudAccessContract.reportIntervalMs`
39
+ * (`reportCloudAccessStatus`) and reads `getCloudAccessBindingState`.
40
+ * `disconnectCloudAccessBinding`, or a disconnect on cloud access, deletes the binding; Cloudly
41
+ * deletes its bearer even when cloud access cannot be reached.
42
+ *
43
+ * Relay (C6). A browser connection for a verified name makes cloud access send
44
+ * `openCloudAccessStream` to the binding's counted socket. The request names no target: the
45
+ * connector always dials `tunnel.cloudaccess.serve.zone` and the host's relay ingress, never an
46
+ * address from the request. After the tunnel's TLS handshake verified, the connector writes the
47
+ * preamble (`cloudAccessTunnelPreamble`) and splices bytes.
48
+ *
49
+ * Both sides state the release of this package they speak (`interfacesVersion` in the enrollment
50
+ * and session registration bodies and in the session registration answer): a side sends a later
51
+ * member, or a later value of a closed list, only to a peer whose release knows it, because every
52
+ * validator here is exact. Refusals are one closed vocabulary, `cloudAccessRefusals`, answered as a
53
+ * `TypedResponseError` whose `errorData` is `ICloudAccessRefusalErrorData`
54
+ * (`readCloudAccessRefusalErrorData`). Validators here judge shape and bounds only; who may do what
55
+ * is cloud access's and Cloudly's.
56
+ */
57
+
58
+ export const cloudAccessContract = Object.freeze({
59
+ /** A `bindingId` or a `streamId` is the lowercase hex of this many random bytes: 32 characters. */
60
+ randomIdBytes: 16,
61
+ /** The controller's bearer is base64url, unpadded, of this many random bytes: 43 characters. */
62
+ bearerRandomBytes: 32,
63
+ /** A pairing code is this many Crockford base32 symbols, 40 bits, shown as `XXXX-XXXX`. */
64
+ pairingCodeSymbols: 8,
65
+ /** How long an enrollment and its pairing code live, in milliseconds: 10 minutes. */
66
+ pairingCodeLifetimeMs: 600_000,
67
+ /** Cloudly reports this often, in milliseconds. */
68
+ reportIntervalMs: 30_000,
69
+ /** Cloud access refuses a report sooner than this after the binding's last accepted one. */
70
+ minimumReportIntervalMs: 10_000,
71
+ /**
72
+ * The largest report: the UTF-8 bytes of its JSON (`measureCloudAccessReportBytes`), 256 KiB. A
73
+ * peer's message cap sits at least 64 KiB above it, so a report one byte above the bound arrives
74
+ * and is answered `report-too-large` rather than cut off with the socket.
75
+ */
76
+ maximumReportBytes: 262_144,
77
+ maximumAttentionItems: 200,
78
+ maximumAttentionTextLength: 500,
79
+ maximumPeople: 1_000,
80
+ maximumLocations: 256,
81
+ maximumVersions: 32,
82
+ /** A DNS name: a `publicOrigin` host, a record name. */
83
+ maximumHostnameLength: 253,
84
+ /** A display name: an organization, a person, an attention item's object. */
85
+ maximumNameLength: 256,
86
+ /** An email address (RFC 5321). */
87
+ maximumEmailLength: 254,
88
+ /** An OpenID Connect subject (OpenID Connect Core 1.0, section 2: at most 255 ASCII characters). */
89
+ maximumSubjectLength: 255,
90
+ /** An idp.global organization id. */
91
+ maximumOrganizationIdLength: 256,
92
+ /** A product name in `ICloudAccessReportVersion`. */
93
+ maximumProductLength: 64,
94
+ /** The text of one name check in `ICloudAccessNameCheck.detail`. */
95
+ maximumCheckDetailLength: 500,
96
+ maximumDnsRecords: 8,
97
+ maximumDnsRecordValueLength: 512,
98
+ /** A stream token is this many random bytes, sent in `openCloudAccessStream` as unpadded base64url. */
99
+ streamTokenBytes: 32,
100
+ /** A stream token is used once, within this many milliseconds of its `openCloudAccessStream`. */
101
+ streamTokenLifetimeMs: 10_000,
102
+ } as const);
103
+
104
+ /**
105
+ * The tunnel preamble (C6, amendment 141a.8): what the connector writes first on a tunnel
106
+ * connection to `tunnel.cloudaccess.serve.zone`, and only after that connection's TLS handshake
107
+ * verified. It is the ASCII bytes of `tag` followed by the 32 raw bytes of the
108
+ * `openCloudAccessStream` token, `byteLength` bytes in all. The tag is a framing magic, not a shape
109
+ * version: the relay reads it before it knows which binding the connection belongs to.
110
+ *
111
+ * - The tag is always the first 13 bytes, so the relay dispatches after one fixed read.
112
+ * - Another layout gets another 13-byte tag, and the relay accepts every tag it knows; it closes a
113
+ * connection that starts with any other bytes.
114
+ */
115
+ const tunnelPreambleTag = 'szca-tunnel-1';
116
+
117
+ export const cloudAccessTunnelPreamble = Object.freeze({
118
+ tag: tunnelPreambleTag,
119
+ tokenBytes: cloudAccessContract.streamTokenBytes,
120
+ byteLength: tunnelPreambleTag.length + cloudAccessContract.streamTokenBytes,
121
+ } as const);
122
+
123
+ /**
124
+ * Every reason cloud access, or Cloudly for `openCloudAccessStream`, answers instead of a request,
125
+ * as a `TypedResponseError` whose `errorData` is `ICloudAccessRefusalErrorData` and whose text
126
+ * carries the detail, never a bearer, a pairing code or a stream token. The list is a vocabulary,
127
+ * not the order a request is checked in; each request's doc (`requests.cloudaccess`) names the
128
+ * refusals it answers. What cloud access answers a person on its own pages (a code entry, Open)
129
+ * belongs to its own API, which stays in the cloudaccess repository.
130
+ */
131
+ export const cloudAccessRefusals = Object.freeze([
132
+ /** The request failed its contract validator; the text carries the validator's sentences. */
133
+ 'request-invalid',
134
+ /**
135
+ * Momentary: a limit of cloud access's was reached: `enrollCloudAccessBinding` beyond 10 per
136
+ * address per hour or 10,000 open in all, or a `getCloudAccessBindingState` re-check asked for
137
+ * too often.
138
+ */
139
+ 'rate-limited',
140
+ /**
141
+ * No live enrollment on this socket has the `bindingId`: its lifetime ended, its socket closed,
142
+ * it was rejected or confirmed already, or it never was this socket's.
143
+ */
144
+ 'enrollment-gone',
145
+ /** `confirmCloudAccessEnrollment` of an enrollment for which nobody has entered the code yet. */
146
+ 'not-claimed',
147
+ /**
148
+ * The socket has not finished its handshake for the call: it has not authenticated
149
+ * (`authenticateCloudAccessBinding`), or not registered its session (`registerCloudAccessSession`).
150
+ */
151
+ 'handshake-incomplete',
152
+ /**
153
+ * No binding authenticates with this `bindingId` and bearer: it was disconnected, its
154
+ * enrollment ended unconfirmed, or the bearer is wrong. One code for all, so a caller learns
155
+ * nothing about which bindings exist. Cloudly treats the binding as ended.
156
+ */
157
+ 'binding-gone',
158
+ /** The bearer is right, but no Administrator has confirmed the enrollment's claim yet. */
159
+ 'not-confirmed',
160
+ /**
161
+ * Momentary: a report sooner than `cloudAccessContract.minimumReportIntervalMs` after the
162
+ * binding's last accepted one. Nothing was stored.
163
+ */
164
+ 'report-too-soon',
165
+ /** A report above `cloudAccessContract.maximumReportBytes` (`measureCloudAccessReportBytes`). */
166
+ 'report-too-large',
167
+ /**
168
+ * The socket is not the binding's counted one: it registered with `active: false`, or another
169
+ * live socket of the binding registered `active: true` with a higher epoch. Cloud access counts no
170
+ * report from it and sends it no stream; Cloudly answers it to an `openCloudAccessStream` on a
171
+ * socket of a site that is not active.
172
+ */
173
+ 'not-active',
174
+ /**
175
+ * Two live sockets of the binding registered `active: true` with the same epoch: cloud access
176
+ * routes nothing and counts no report until one of them leaves, and raises an alert naming the
177
+ * conflict. It judges the controller's state, so it is no momentary refusal.
178
+ */
179
+ 'epoch-conflict',
180
+ /** Momentary: Cloudly refuses an `openCloudAccessStream` over its connector's stream limits. */
181
+ 'stream-limit',
182
+ /** Momentary: cloud access could not read or write its records; nothing was changed. */
183
+ 'cloud-access-unavailable',
184
+ ] as const);
185
+
186
+ /** One of the reasons cloud access or Cloudly answers instead of a request. */
187
+ export type TCloudAccessRefusal = typeof cloudAccessRefusals[number];
188
+
189
+ /** The refusals that describe the refusing side's own momentary state rather than a judgement. */
190
+ export const cloudAccessMomentaryRefusals = Object.freeze([
191
+ 'rate-limited',
192
+ 'report-too-soon',
193
+ 'stream-limit',
194
+ 'cloud-access-unavailable',
195
+ ] as const satisfies readonly TCloudAccessRefusal[]);
196
+
197
+ /** One of the momentary cloud access refusals. */
198
+ export type TCloudAccessMomentaryRefusal = typeof cloudAccessMomentaryRefusals[number];
199
+
200
+ /** A cloud access refusal as `TypedResponseError.errorData`; the error text carries its detail. */
201
+ export interface ICloudAccessRefusalErrorData {
202
+ code: TCloudAccessRefusal;
203
+ /**
204
+ * True exactly for `cloudAccessMomentaryRefusals`: the same request may be sent again later.
205
+ * Every other refusal answers the same request again until the state the code names changed.
206
+ */
207
+ retryable: boolean;
208
+ }
209
+
210
+ /** True for one of `cloudAccessRefusals`. */
211
+ export const isCloudAccessRefusal = (valueArg: unknown): valueArg is TCloudAccessRefusal => (
212
+ (cloudAccessRefusals as readonly unknown[]).includes(valueArg)
213
+ );
214
+
215
+ /** True for one of `cloudAccessMomentaryRefusals`. */
216
+ export const isCloudAccessMomentaryRefusal = (valueArg: unknown): valueArg is TCloudAccessMomentaryRefusal => (
217
+ (cloudAccessMomentaryRefusals as readonly unknown[]).includes(valueArg)
218
+ );
219
+
220
+ /** The `errorData` a cloud access refusal is answered with. */
221
+ export const createCloudAccessRefusalErrorData = (codeArg: TCloudAccessRefusal): ICloudAccessRefusalErrorData => (
222
+ Object.freeze({ code: codeArg, retryable: isCloudAccessMomentaryRefusal(codeArg) })
223
+ );
224
+
225
+ const refusalErrorDataKeyList = ['code', 'retryable'] as const;
226
+ const refusalErrorDataKeys: TCompleteKeyList<ICloudAccessRefusalErrorData, typeof refusalErrorDataKeyList> =
227
+ refusalErrorDataKeyList;
228
+
229
+ /**
230
+ * The cloud access refusal an error payload states, or `null` when it is not exactly one: a payload
231
+ * with another member, an unknown code or a `retryable` that disagrees with the code reads as no
232
+ * answer, never as a verdict.
233
+ */
234
+ export const readCloudAccessRefusalErrorData = (valueArg: unknown): ICloudAccessRefusalErrorData | null => {
235
+ const record = readExactDataRecord(valueArg, refusalErrorDataKeys);
236
+ if (record === null || !isCloudAccessRefusal(record.code)
237
+ || record.retryable !== isCloudAccessMomentaryRefusal(record.code)) {
238
+ return null;
239
+ }
240
+ return createCloudAccessRefusalErrorData(record.code);
241
+ };
242
+
243
+ /**
244
+ * A pairing code in its display form, the one Cloudly validates and shows: 8 uppercase Crockford
245
+ * base32 symbols (40 bits) as `XXXX-XXXX`. Only cloud access mints codes and reads typed input; how
246
+ * it normalizes what a person typed is its own page's rule, not this contract's (amendment 141a.3).
247
+ */
248
+ const pairingCodeDisplayPattern = /^[0-9A-HJKMNP-TV-Z]{4}-[0-9A-HJKMNP-TV-Z]{4}$/;
249
+
250
+ /** True for a pairing code in its display form: 8 uppercase Crockford base32 symbols as `XXXX-XXXX`. */
251
+ export const isCloudAccessPairingCode = (valueArg: unknown): valueArg is string => (
252
+ typeof valueArg === 'string' && pairingCodeDisplayPattern.test(valueArg)
253
+ );
254
+
255
+ /** The body of `enrollCloudAccessBinding` (`validateEnrollCloudAccessBindingRequest`). */
256
+ export interface IEnrollCloudAccessBindingRequest {
257
+ /** Self-reported and for display only; cloud access keys everything by `bindingId`. */
258
+ controllerId: string;
259
+ /**
260
+ * The controller's public origin (`validateCloudAccessPublicOrigin`): `https`, port 443, no
261
+ * path. Its host is the one name the binding may route.
262
+ */
263
+ publicOrigin: string;
264
+ /** The Cloudly release that enrolls (`data.isReleaseVersion`), for display. */
265
+ version: string;
266
+ /** The release of this package Cloudly speaks (`data.isReleaseVersion`). */
267
+ interfacesVersion: string;
268
+ /**
269
+ * The SHA-256 of the UTF-8 of the bearer Cloudly created for itself: 64 lowercase hex characters.
270
+ * The bearer itself never leaves Cloudly's secret store.
271
+ */
272
+ bearerSha256: string;
273
+ }
274
+
275
+ /** What `enrollCloudAccessBinding` answers (`validateCloudAccessEnrollment`). */
276
+ export interface ICloudAccessEnrollment {
277
+ /** Random, assigned by cloud access: `cloudAccessContract.randomIdBytes` bytes as lowercase hex. */
278
+ bindingId: string;
279
+ /** In its display form, `XXXX-XXXX` (`isCloudAccessPairingCode`). */
280
+ pairingCode: string;
281
+ /**
282
+ * Unix milliseconds on cloud access's clock when the enrollment and its code end. It never moves;
283
+ * Cloudly keeps it for as long as the enrollment lives on its socket.
284
+ */
285
+ expiresAt: number;
286
+ }
287
+
288
+ /** A claim recorded by a code entry, waiting for the controller's Administrator (C3 step 3). */
289
+ export interface ICloudAccessPendingClaim {
290
+ /** The idp.global organization the claimant picked: its id, never its slug. */
291
+ organizationId: string;
292
+ organizationName: string;
293
+ /** The person who entered the code, as idp.global names them. */
294
+ claimantSubject: string;
295
+ claimantName: string;
296
+ claimantEmail: string;
297
+ }
298
+
299
+ /** What `getCloudAccessEnrollmentState` answers (`validateCloudAccessEnrollmentState`). */
300
+ export interface ICloudAccessEnrollmentState {
301
+ /** `waiting` until a person enters the code, then `claimed` until the enrollment ends. */
302
+ state: 'waiting' | 'claimed';
303
+ /** `null` exactly while `waiting`. */
304
+ claim: ICloudAccessPendingClaim | null;
305
+ }
306
+
307
+ /**
308
+ * The body of `getCloudAccessEnrollmentState`, `confirmCloudAccessEnrollment` and
309
+ * `rejectCloudAccessEnrollment` (`validateCloudAccessEnrollmentHandle`).
310
+ */
311
+ export interface ICloudAccessEnrollmentHandle {
312
+ bindingId: string;
313
+ }
314
+
315
+ /**
316
+ * The body of `authenticateCloudAccessBinding` (`validateAuthenticateCloudAccessBindingRequest`);
317
+ * exclude it from logs.
318
+ */
319
+ export interface IAuthenticateCloudAccessBindingRequest {
320
+ bindingId: string;
321
+ /**
322
+ * Base64url, unpadded, of `cloudAccessContract.bearerRandomBytes` random bytes: exactly 43
323
+ * characters. Never logged, never part of a refusal.
324
+ */
325
+ bearer: string;
326
+ }
327
+
328
+ /** The body of `registerCloudAccessSession` (`validateRegisterCloudAccessSessionRequest`). */
329
+ export interface IRegisterCloudAccessSessionRequest {
330
+ /** Self-reported and for display only. */
331
+ controllerId: string;
332
+ /** The controller epoch this site holds (`IControllerPeerSet.epoch`). */
333
+ epoch: number;
334
+ /** Whether this site is the active controller; a shadow says `false`. */
335
+ active: boolean;
336
+ /** The Cloudly release this site runs (`data.isReleaseVersion`), for display. */
337
+ version: string;
338
+ /** The release of this package this site speaks (`data.isReleaseVersion`). */
339
+ interfacesVersion: string;
340
+ }
341
+
342
+ /** What `registerCloudAccessSession` answers (`validateRegisterCloudAccessSessionResponse`). */
343
+ export interface IRegisterCloudAccessSessionResponse {
344
+ /** The release of this package cloud access speaks (`data.isReleaseVersion`). */
345
+ interfacesVersion: string;
346
+ }
347
+
348
+ /** One release some of the controller's components run, and the update it is offered. */
349
+ export interface ICloudAccessReportVersion {
350
+ /**
351
+ * The component as the controller names it, for display only (`cloudly`, `onebox`, `kubernetes`,
352
+ * `dcrouter`): lowercase letters, digits and hyphens. Each `(product, running)` once per report.
353
+ */
354
+ product: string;
355
+ /** The release they run (`data.isReleaseVersion`). */
356
+ running: string;
357
+ /**
358
+ * The newest release the controller is offered for them (`data.isReleaseVersion`), or `null`
359
+ * when they run it; cloud access never asks a registry itself.
360
+ */
361
+ offered: string | null;
362
+ /** How many of them run `running`: a positive safe integer. */
363
+ count: number;
364
+ }
365
+
366
+ /** Counts of the controller's fleet. */
367
+ export interface ICloudAccessReportCounts {
368
+ nodes: number;
369
+ /** Of `nodes`, the offline ones. */
370
+ offlineNodes: number;
371
+ services: number;
372
+ }
373
+
374
+ /** The controller roles a location can hold in a report. */
375
+ export const cloudAccessLocationRoles = Object.freeze(['active', 'shadow', 'none'] as const);
376
+
377
+ /** One of `cloudAccessLocationRoles`. */
378
+ export type TCloudAccessLocationRole = typeof cloudAccessLocationRoles[number];
379
+
380
+ /** One of the controller's locations. */
381
+ export interface ICloudAccessReportLocation {
382
+ /** `data.isLocationName`; each name once per report. */
383
+ name: string;
384
+ /** The controller site it holds: the active one, a shadow, or none (edges or nodes only). */
385
+ role: TCloudAccessLocationRole;
386
+ /** For a `shadow`, whether it is in sync with the active; `null` for every other role. */
387
+ inSync: boolean | null;
388
+ }
389
+
390
+ /** The severities of an attention item, Cloudly's own. */
391
+ export const cloudAccessAttentionSeverities = Object.freeze(['failed', 'warning'] as const);
392
+
393
+ /** One of `cloudAccessAttentionSeverities`. */
394
+ export type TCloudAccessAttentionSeverity = typeof cloudAccessAttentionSeverities[number];
395
+
396
+ /** The kinds of object an attention item is about, Cloudly's own. */
397
+ export const cloudAccessAttentionKinds = Object.freeze(['service', 'node', 'domain', 'backup'] as const);
398
+
399
+ /** One of `cloudAccessAttentionKinds`. */
400
+ export type TCloudAccessAttentionKind = typeof cloudAccessAttentionKinds[number];
401
+
402
+ /**
403
+ * One thing on the controller an administrator should look at. Cloud access keys its alert
404
+ * history by `(bindingId, key)` and renders every string as text only, never as HTML.
405
+ */
406
+ export interface ICloudAccessAttentionItem {
407
+ /**
408
+ * Stable while the condition lasts (`service:<id>`), under `data.validateControllerIdentifier`'s
409
+ * rule. One key outside it refuses the whole report: the sender checks before it sends.
410
+ */
411
+ key: string;
412
+ severity: TCloudAccessAttentionSeverity;
413
+ kind: TCloudAccessAttentionKind;
414
+ /** The object's display name (a service, a node's hostname, a domain). */
415
+ object: string;
416
+ /** The location the object stands in (`data.isLocationName`), or `null` when it stands in none. */
417
+ location: string | null;
418
+ /**
419
+ * Unix milliseconds on the controller's clock since when it holds, or `null` when unknown; never
420
+ * a time in the future, such as an expiry.
421
+ */
422
+ since: number | null;
423
+ /** At most `cloudAccessContract.maximumAttentionTextLength` characters. */
424
+ text: string;
425
+ }
426
+
427
+ /** The Cloudly roles of a human user (`IUser.data.role`). */
428
+ export const cloudAccessPersonRoles = Object.freeze(['admin', 'user'] as const satisfies readonly IUser['data']['role'][]);
429
+
430
+ /** One of `cloudAccessPersonRoles`. */
431
+ export type TCloudAccessPersonRole = typeof cloudAccessPersonRoles[number];
432
+
433
+ /** One person the controller knows by an idp.global subject, with their Cloudly role. */
434
+ export interface ICloudAccessPerson {
435
+ subject: string;
436
+ role: TCloudAccessPersonRole;
437
+ }
438
+
439
+ /**
440
+ * The controller's people: users linked to idp.global, by subject. For display only, never
441
+ * authority. `issuer` is the idp.global issuer the controller signs in with (a canonical `https`
442
+ * origin); cloud access shows the map only when it is the issuer it signs in with itself, and a
443
+ * controller lists no person linked to another issuer. Names come from cloud access's own sign-in
444
+ * records, not from the report.
445
+ */
446
+ export interface ICloudAccessPeopleMap {
447
+ issuer: string;
448
+ /** Each subject once, at most `cloudAccessContract.maximumPeople`. */
449
+ entries: ICloudAccessPerson[];
450
+ }
451
+
452
+ /** One report (`validateCloudAccessReport`), the body of `reportCloudAccessStatus`. */
453
+ export interface ICloudAccessReport {
454
+ /** Cloudly's own health verdict, the one `cloudlyStatusPath` answers. */
455
+ healthy: boolean;
456
+ versions: ICloudAccessReportVersion[];
457
+ counts: ICloudAccessReportCounts;
458
+ locations: ICloudAccessReportLocation[];
459
+ /** Most urgent first, each `key` once, at most `cloudAccessContract.maximumAttentionItems`. */
460
+ attention: ICloudAccessAttentionItem[];
461
+ /** `null` while the controller has no idp.global sign-in. */
462
+ people: ICloudAccessPeopleMap | null;
463
+ }
464
+
465
+ /** The states of one hostname proof check (C4). */
466
+ export const cloudAccessNameCheckStates = Object.freeze([
467
+ /** Not checked yet. */
468
+ 'unchecked',
469
+ 'passing',
470
+ /** A definite negative answer: the route goes at once. */
471
+ 'failing',
472
+ /** The lookup failed: the previous verdict holds for at most 72 hours, then the route goes. */
473
+ 'lookup-error',
474
+ ] as const);
475
+
476
+ /** One of `cloudAccessNameCheckStates`. */
477
+ export type TCloudAccessNameCheckState = typeof cloudAccessNameCheckStates[number];
478
+
479
+ /** One hostname proof check as cloud access last ran it. */
480
+ export interface ICloudAccessNameCheck {
481
+ state: TCloudAccessNameCheckState;
482
+ /** Unix milliseconds on cloud access's clock; `null` exactly while `unchecked`. */
483
+ checkedAt: number | null;
484
+ /** Why it is not passing, at most `cloudAccessContract.maximumCheckDetailLength` characters. */
485
+ detail: string | null;
486
+ }
487
+
488
+ /** The record types a binding asks its owner to publish. */
489
+ export const cloudAccessDnsRecordTypes = Object.freeze(['TXT', 'A', 'AAAA', 'CAA'] as const);
490
+
491
+ /** One of `cloudAccessDnsRecordTypes`. */
492
+ export type TCloudAccessDnsRecordType = typeof cloudAccessDnsRecordTypes[number];
493
+
494
+ /** One record to publish, ready to copy. */
495
+ export interface ICloudAccessDnsRecord {
496
+ type: TCloudAccessDnsRecordType;
497
+ /** The record's name, a lowercase DNS name without the trailing dot. */
498
+ name: string;
499
+ /** The record's value in presentation format, at most `maximumDnsRecordValueLength` characters. */
500
+ value: string;
501
+ }
502
+
503
+ /** What `getCloudAccessBindingState` answers (`validateCloudAccessBindingState`). */
504
+ export interface ICloudAccessBindingState {
505
+ bindingId: string;
506
+ /** The idp.global organization the binding belongs to. */
507
+ organizationId: string;
508
+ organizationName: string;
509
+ /** The one name the binding may route: the host of the enrolled `publicOrigin`. */
510
+ hostname: string;
511
+ /**
512
+ * The hostname proof (C4): `txt`, `TXT _cloudaccess.<host>` holds `ca1=<bindingId>`; `address`,
513
+ * the name has A/AAAA records directly, with no CNAME or DNAME on the way; `caa`, the effective
514
+ * CAA set allows exactly `letsencrypt.org` with `validationmethods=dns-01`.
515
+ */
516
+ checks: {
517
+ txt: ICloudAccessNameCheck;
518
+ address: ICloudAccessNameCheck;
519
+ caa: ICloudAccessNameCheck;
520
+ };
521
+ /** Diagnostic, never a condition: whether the name's A/AAAA point at the relay; `null` unchecked. */
522
+ pointsAtRelay: boolean | null;
523
+ /** Whether the relay routes the name now. */
524
+ routed: boolean;
525
+ /** The records the name's owner publishes, ready to copy; 1 to `maximumDnsRecords`. */
526
+ records: ICloudAccessDnsRecord[];
527
+ }
528
+
529
+ /** The body of `getCloudAccessBindingState` (`validateGetCloudAccessBindingStateRequest`). */
530
+ export interface IGetCloudAccessBindingStateRequest {
531
+ /**
532
+ * Runs the hostname proof now, which only brings the scheduled check forward, before answering;
533
+ * refused `rate-limited` when asked too often.
534
+ */
535
+ recheck: boolean;
536
+ }
537
+
538
+ /**
539
+ * The body of `openCloudAccessStream` (`validateOpenCloudAccessStreamRequest`). It names no target:
540
+ * the connector dials `tunnel.cloudaccess.serve.zone` and the host's relay ingress, never an address
541
+ * taken from a request.
542
+ */
543
+ export interface IOpenCloudAccessStreamRequest {
544
+ /** Random, assigned by cloud access: `cloudAccessContract.randomIdBytes` bytes as lowercase hex. */
545
+ streamId: string;
546
+ /**
547
+ * Unpadded base64url of `cloudAccessContract.streamTokenBytes` random bytes: 43 characters. Used
548
+ * once, valid `streamTokenLifetimeMs`, bound to the binding; written raw in the preamble. Never logged.
549
+ */
550
+ token: string;
551
+ /**
552
+ * The browser's address as the relay saw it, canonical (`192.0.2.1`, RFC 5952 for IPv6, never
553
+ * IPv4-mapped). Cloudly records it as reported, never as the peer.
554
+ */
555
+ clientAddress: string;
556
+ }
557
+
558
+ const randomIdPattern = /^[0-9a-f]{32}$/;
559
+ const productPattern = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
560
+
561
+ const validateRandomId = (valueArg: unknown, pathArg: string): string[] => (
562
+ typeof valueArg === 'string' && randomIdPattern.test(valueArg)
563
+ ? []
564
+ : [`${pathArg} must be ${cloudAccessContract.randomIdBytes * 2} lowercase hex characters`]
565
+ );
566
+
567
+ const validateBase64url32 = (valueArg: unknown, pathArg: string): string[] => (
568
+ isCanonicalBase64url32(valueArg)
569
+ ? []
570
+ : [`${pathArg} must be the base64url of 32 random bytes: 43 characters`]
571
+ );
572
+
573
+ const validateBoundedString = (valueArg: unknown, pathArg: string, maximumLengthArg: number): string[] => (
574
+ typeof valueArg === 'string' && valueArg.length > 0 && valueArg.length <= maximumLengthArg
575
+ ? []
576
+ : [`${pathArg} must be a string of 1 to ${maximumLengthArg} characters`]
577
+ );
578
+
579
+ const validateUnixMilliseconds = (valueArg: unknown, pathArg: string): string[] => (
580
+ validateControllerNonNegativeInteger(valueArg, pathArg)
581
+ );
582
+
583
+ const validateNullable = (
584
+ valueArg: unknown,
585
+ pathArg: string,
586
+ validatorArg: (valueArg: unknown, pathArg: string) => string[],
587
+ ): string[] => (valueArg === null ? [] : validatorArg(valueArg, pathArg));
588
+
589
+ const validateBoolean = (valueArg: unknown, pathArg: string): string[] => (
590
+ typeof valueArg === 'boolean' ? [] : [`${pathArg} must be a boolean`]
591
+ );
592
+
593
+ const validateReleaseVersion = (valueArg: unknown, pathArg: string): string[] => (
594
+ isReleaseVersion(valueArg) ? [] : [`${pathArg} must be a release version such as 1.2.3`]
595
+ );
596
+
597
+ const validateOneOf = (valueArg: unknown, pathArg: string, valuesArg: readonly string[]): string[] => (
598
+ valuesArg.includes(valueArg as string) ? [] : [`${pathArg} must be one of ${valuesArg.join(', ')}`]
599
+ );
600
+
601
+ const validateLocationName = (valueArg: unknown, pathArg: string): string[] => (
602
+ isLocationName(valueArg) ? [] : [`${pathArg} must be a location name: one lowercase RFC 1123 label`]
603
+ );
604
+
605
+ /** A lowercase DNS name of two or more labels whose last label is not all digits (no address literal). */
606
+ const isCloudAccessHostname = (valueArg: unknown): valueArg is string => (
607
+ isGatewayClientHostname(valueArg)
608
+ && valueArg.length <= cloudAccessContract.maximumHostnameLength
609
+ && !/^[0-9]+$/.test(valueArg.slice(valueArg.lastIndexOf('.') + 1))
610
+ );
611
+
612
+ const validateHostname = (valueArg: unknown, pathArg: string): string[] => (
613
+ isCloudAccessHostname(valueArg)
614
+ ? []
615
+ : [`${pathArg} must be a lowercase DNS name of two or more labels and at most `
616
+ + `${cloudAccessContract.maximumHostnameLength} characters`]
617
+ );
618
+
619
+ /** A list of at most `maximumArg` elements, or the refusal naming the bound. */
620
+ const readList = (
621
+ valueArg: unknown,
622
+ pathArg: string,
623
+ maximumArg: number,
624
+ nounArg: string,
625
+ ): { elements: unknown[] | null; errors: string[] } => {
626
+ const elements = readDataElements(valueArg, maximumArg);
627
+ return elements === null
628
+ ? { elements: null, errors: [`${pathArg} must be a dense list of at most ${maximumArg} ${nounArg}`] }
629
+ : { elements, errors: [] };
630
+ };
631
+
632
+ /** The refusal for a list whose values repeat, judged only over its well-formed elements. */
633
+ const validateUnique = (valuesArg: unknown[], pathArg: string, nounArg: string): string[] => {
634
+ const strings = valuesArg.filter((valueArg): valueArg is string => typeof valueArg === 'string');
635
+ return new Set(strings).size === strings.length ? [] : [`${pathArg} must name each ${nounArg} once`];
636
+ };
637
+
638
+ /**
639
+ * A controller's `publicOrigin` as cloud access binds it: a canonical `https` origin on port 443
640
+ * (no explicit port), without userinfo, path, query or fragment, whose host is a DNS name of two
641
+ * or more labels (no address literal) and is neither `serve.zone` nor below it.
642
+ */
643
+ export const validateCloudAccessPublicOrigin = (valueArg: unknown, pathArg = 'public origin'): string[] => {
644
+ const maximum = 'https://'.length + cloudAccessContract.maximumHostnameLength;
645
+ const errors = validateControllerOrigin(valueArg, pathArg, maximum);
646
+ if (errors.length > 0) {
647
+ return errors;
648
+ }
649
+ const url = new URL(valueArg as string);
650
+ if (url.port !== '') {
651
+ errors.push(`${pathArg} must use port 443, stated by no port`);
652
+ }
653
+ if (!isCloudAccessHostname(url.hostname)) {
654
+ errors.push(`${pathArg} host must be a lowercase DNS name of two or more labels, not an address`);
655
+ } else if (url.hostname === 'serve.zone' || url.hostname.endsWith('.serve.zone')) {
656
+ errors.push(`${pathArg} host must not be serve.zone or a name below it`);
657
+ }
658
+ return errors;
659
+ };
660
+
661
+ const enrollKeyList = ['controllerId', 'publicOrigin', 'version', 'interfacesVersion', 'bearerSha256'] as const;
662
+ const enrollKeys: TCompleteKeyList<IEnrollCloudAccessBindingRequest, typeof enrollKeyList> = enrollKeyList;
663
+
664
+ /** Validates an `enrollCloudAccessBinding` body and names every reason it is refused. */
665
+ export const validateEnrollCloudAccessBindingRequest = (
666
+ valueArg: unknown,
667
+ pathArg = 'enroll cloud access binding request',
668
+ ): string[] => {
669
+ const record = readExactDataRecord(valueArg, enrollKeys);
670
+ return record === null
671
+ ? [`${pathArg} must use its exact schema`]
672
+ : [
673
+ ...validateControllerIdentifier(record.controllerId, `${pathArg} controllerId`),
674
+ ...validateCloudAccessPublicOrigin(record.publicOrigin, `${pathArg} publicOrigin`),
675
+ ...validateReleaseVersion(record.version, `${pathArg} version`),
676
+ ...validateReleaseVersion(record.interfacesVersion, `${pathArg} interfacesVersion`),
677
+ ...(isSha256Hex(record.bearerSha256)
678
+ ? []
679
+ : [`${pathArg} bearerSha256 must be a SHA-256 digest of 64 lowercase hex characters`]),
680
+ ];
681
+ };
682
+
683
+ const enrollmentKeyList = ['bindingId', 'pairingCode', 'expiresAt'] as const;
684
+ const enrollmentKeys: TCompleteKeyList<ICloudAccessEnrollment, typeof enrollmentKeyList> = enrollmentKeyList;
685
+
686
+ /** Validates what `enrollCloudAccessBinding` answers; Cloudly checks it before it shows the code. */
687
+ export const validateCloudAccessEnrollment = (valueArg: unknown, pathArg = 'cloud access enrollment'): string[] => {
688
+ const record = readExactDataRecord(valueArg, enrollmentKeys);
689
+ return record === null
690
+ ? [`${pathArg} must use its exact schema`]
691
+ : [
692
+ ...validateRandomId(record.bindingId, `${pathArg} bindingId`),
693
+ ...(isCloudAccessPairingCode(record.pairingCode)
694
+ ? []
695
+ : [`${pathArg} pairingCode must be 8 Crockford base32 symbols shown as XXXX-XXXX`]),
696
+ ...validateUnixMilliseconds(record.expiresAt, `${pathArg} expiresAt`),
697
+ ];
698
+ };
699
+
700
+ const claimKeyList = [
701
+ 'organizationId', 'organizationName', 'claimantSubject', 'claimantName', 'claimantEmail',
702
+ ] as const;
703
+ const claimKeys: TCompleteKeyList<ICloudAccessPendingClaim, typeof claimKeyList> = claimKeyList;
704
+ const enrollmentStateKeyList = ['state', 'claim'] as const;
705
+ const enrollmentStateKeys: TCompleteKeyList<ICloudAccessEnrollmentState, typeof enrollmentStateKeyList> =
706
+ enrollmentStateKeyList;
707
+
708
+ const validatePendingClaim = (valueArg: unknown, pathArg: string): string[] => {
709
+ const record = readExactDataRecord(valueArg, claimKeys);
710
+ const { maximumOrganizationIdLength, maximumNameLength, maximumSubjectLength, maximumEmailLength } =
711
+ cloudAccessContract;
712
+ return record === null
713
+ ? [`${pathArg} must use its exact schema`]
714
+ : [
715
+ ...validateBoundedString(record.organizationId, `${pathArg} organizationId`, maximumOrganizationIdLength),
716
+ ...validateBoundedString(record.organizationName, `${pathArg} organizationName`, maximumNameLength),
717
+ ...validateBoundedString(record.claimantSubject, `${pathArg} claimantSubject`, maximumSubjectLength),
718
+ ...validateBoundedString(record.claimantName, `${pathArg} claimantName`, maximumNameLength),
719
+ ...validateBoundedString(record.claimantEmail, `${pathArg} claimantEmail`, maximumEmailLength),
720
+ ];
721
+ };
722
+
723
+ /**
724
+ * Validates what `getCloudAccessEnrollmentState` answers; Cloudly checks it before it asks for a
725
+ * confirmation.
726
+ */
727
+ export const validateCloudAccessEnrollmentState = (
728
+ valueArg: unknown,
729
+ pathArg = 'cloud access enrollment state',
730
+ ): string[] => {
731
+ const record = readExactDataRecord(valueArg, enrollmentStateKeys);
732
+ if (record === null) {
733
+ return [`${pathArg} must use its exact schema`];
734
+ }
735
+ const errors = validateOneOf(record.state, `${pathArg} state`, ['waiting', 'claimed']);
736
+ if (record.state === 'waiting' && record.claim !== null) {
737
+ errors.push(`${pathArg} claim must be null while waiting`);
738
+ } else if (record.state === 'claimed') {
739
+ errors.push(...validatePendingClaim(record.claim, `${pathArg} claim`));
740
+ }
741
+ return errors;
742
+ };
743
+
744
+ const handleKeyList = ['bindingId'] as const;
745
+ const handleKeys: TCompleteKeyList<ICloudAccessEnrollmentHandle, typeof handleKeyList> = handleKeyList;
746
+
747
+ /**
748
+ * Validates a `getCloudAccessEnrollmentState`, `confirmCloudAccessEnrollment` or
749
+ * `rejectCloudAccessEnrollment` body.
750
+ */
751
+ export const validateCloudAccessEnrollmentHandle = (
752
+ valueArg: unknown,
753
+ pathArg = 'cloud access enrollment handle',
754
+ ): string[] => {
755
+ const record = readExactDataRecord(valueArg, handleKeys);
756
+ return record === null
757
+ ? [`${pathArg} must use its exact schema`]
758
+ : validateRandomId(record.bindingId, `${pathArg} bindingId`);
759
+ };
760
+
761
+ const authenticateKeyList = ['bindingId', 'bearer'] as const;
762
+ const authenticateKeys: TCompleteKeyList<IAuthenticateCloudAccessBindingRequest, typeof authenticateKeyList> =
763
+ authenticateKeyList;
764
+
765
+ /** Validates an `authenticateCloudAccessBinding` body; no refusal carries the bearer. */
766
+ export const validateAuthenticateCloudAccessBindingRequest = (
767
+ valueArg: unknown,
768
+ pathArg = 'authenticate cloud access binding request',
769
+ ): string[] => {
770
+ const record = readExactDataRecord(valueArg, authenticateKeys);
771
+ return record === null
772
+ ? [`${pathArg} must use its exact schema`]
773
+ : [
774
+ ...validateRandomId(record.bindingId, `${pathArg} bindingId`),
775
+ ...validateBase64url32(record.bearer, `${pathArg} bearer`),
776
+ ];
777
+ };
778
+
779
+ const registerKeyList = ['controllerId', 'epoch', 'active', 'version', 'interfacesVersion'] as const;
780
+ const registerKeys: TCompleteKeyList<IRegisterCloudAccessSessionRequest, typeof registerKeyList> =
781
+ registerKeyList;
782
+ const registerResponseKeyList = ['interfacesVersion'] as const;
783
+ const registerResponseKeys: TCompleteKeyList<IRegisterCloudAccessSessionResponse, typeof registerResponseKeyList> =
784
+ registerResponseKeyList;
785
+
786
+ /** Validates a `registerCloudAccessSession` body. */
787
+ export const validateRegisterCloudAccessSessionRequest = (
788
+ valueArg: unknown,
789
+ pathArg = 'register cloud access session request',
790
+ ): string[] => {
791
+ const record = readExactDataRecord(valueArg, registerKeys);
792
+ return record === null
793
+ ? [`${pathArg} must use its exact schema`]
794
+ : [
795
+ ...validateControllerIdentifier(record.controllerId, `${pathArg} controllerId`),
796
+ ...validateControllerCounter(record.epoch, `${pathArg} epoch`),
797
+ ...validateBoolean(record.active, `${pathArg} active`),
798
+ ...validateReleaseVersion(record.version, `${pathArg} version`),
799
+ ...validateReleaseVersion(record.interfacesVersion, `${pathArg} interfacesVersion`),
800
+ ];
801
+ };
802
+
803
+ /** Validates what `registerCloudAccessSession` answers. */
804
+ export const validateRegisterCloudAccessSessionResponse = (
805
+ valueArg: unknown,
806
+ pathArg = 'register cloud access session response',
807
+ ): string[] => {
808
+ const record = readExactDataRecord(valueArg, registerResponseKeys);
809
+ return record === null
810
+ ? [`${pathArg} must use its exact schema`]
811
+ : validateReleaseVersion(record.interfacesVersion, `${pathArg} interfacesVersion`);
812
+ };
813
+
814
+ const versionKeyList = ['product', 'running', 'offered', 'count'] as const;
815
+ const versionKeys: TCompleteKeyList<ICloudAccessReportVersion, typeof versionKeyList> = versionKeyList;
816
+ const countsKeyList = ['nodes', 'offlineNodes', 'services'] as const;
817
+ const countsKeys: TCompleteKeyList<ICloudAccessReportCounts, typeof countsKeyList> = countsKeyList;
818
+ const locationKeyList = ['name', 'role', 'inSync'] as const;
819
+ const locationKeys: TCompleteKeyList<ICloudAccessReportLocation, typeof locationKeyList> = locationKeyList;
820
+ const attentionKeyList = ['key', 'severity', 'kind', 'object', 'location', 'since', 'text'] as const;
821
+ const attentionKeys: TCompleteKeyList<ICloudAccessAttentionItem, typeof attentionKeyList> = attentionKeyList;
822
+ const personKeyList = ['subject', 'role'] as const;
823
+ const personKeys: TCompleteKeyList<ICloudAccessPerson, typeof personKeyList> = personKeyList;
824
+ const peopleKeyList = ['issuer', 'entries'] as const;
825
+ const peopleKeys: TCompleteKeyList<ICloudAccessPeopleMap, typeof peopleKeyList> = peopleKeyList;
826
+ const reportKeyList = ['healthy', 'versions', 'counts', 'locations', 'attention', 'people'] as const;
827
+ const reportKeys: TCompleteKeyList<ICloudAccessReport, typeof reportKeyList> = reportKeyList;
828
+
829
+ const validateVersion = (valueArg: unknown, pathArg: string): string[] => {
830
+ const record = readExactDataRecord(valueArg, versionKeys);
831
+ if (record === null) {
832
+ return [`${pathArg} must use its exact schema`];
833
+ }
834
+ return [
835
+ ...(typeof record.product === 'string' && productPattern.test(record.product)
836
+ ? []
837
+ : [`${pathArg} product must be 1 to ${cloudAccessContract.maximumProductLength} lowercase letters, `
838
+ + 'digits or hyphens']),
839
+ ...validateReleaseVersion(record.running, `${pathArg} running`),
840
+ ...validateNullable(record.offered, `${pathArg} offered`, validateReleaseVersion),
841
+ ...validateControllerCounter(record.count, `${pathArg} count`),
842
+ ];
843
+ };
844
+
845
+ const validateCounts = (valueArg: unknown, pathArg: string): string[] => {
846
+ const record = readExactDataRecord(valueArg, countsKeys);
847
+ if (record === null) {
848
+ return [`${pathArg} must use its exact schema`];
849
+ }
850
+ const errors = [
851
+ ...validateControllerNonNegativeInteger(record.nodes, `${pathArg} nodes`),
852
+ ...validateControllerNonNegativeInteger(record.offlineNodes, `${pathArg} offlineNodes`),
853
+ ...validateControllerNonNegativeInteger(record.services, `${pathArg} services`),
854
+ ];
855
+ if (errors.length === 0 && (record.offlineNodes as number) > (record.nodes as number)) {
856
+ errors.push(`${pathArg} offlineNodes must not exceed nodes`);
857
+ }
858
+ return errors;
859
+ };
860
+
861
+ const validateLocation = (valueArg: unknown, pathArg: string): string[] => {
862
+ const record = readExactDataRecord(valueArg, locationKeys);
863
+ if (record === null) {
864
+ return [`${pathArg} must use its exact schema`];
865
+ }
866
+ const errors = [
867
+ ...validateLocationName(record.name, `${pathArg} name`),
868
+ ...validateOneOf(record.role, `${pathArg} role`, cloudAccessLocationRoles),
869
+ ];
870
+ if (record.role === 'shadow') {
871
+ errors.push(...validateBoolean(record.inSync, `${pathArg} inSync`));
872
+ } else if (record.inSync !== null) {
873
+ errors.push(`${pathArg} inSync must be null for a location that holds no shadow`);
874
+ }
875
+ return errors;
876
+ };
877
+
878
+ const validateAttentionItem = (valueArg: unknown, pathArg: string): string[] => {
879
+ const record = readExactDataRecord(valueArg, attentionKeys);
880
+ if (record === null) {
881
+ return [`${pathArg} must use its exact schema`];
882
+ }
883
+ return [
884
+ ...validateControllerIdentifier(record.key, `${pathArg} key`),
885
+ ...validateOneOf(record.severity, `${pathArg} severity`, cloudAccessAttentionSeverities),
886
+ ...validateOneOf(record.kind, `${pathArg} kind`, cloudAccessAttentionKinds),
887
+ ...validateBoundedString(record.object, `${pathArg} object`, cloudAccessContract.maximumNameLength),
888
+ ...validateNullable(record.location, `${pathArg} location`, validateLocationName),
889
+ ...validateNullable(record.since, `${pathArg} since`, validateUnixMilliseconds),
890
+ ...validateBoundedString(record.text, `${pathArg} text`, cloudAccessContract.maximumAttentionTextLength),
891
+ ];
892
+ };
893
+
894
+ const validatePerson = (valueArg: unknown, pathArg: string): string[] => {
895
+ const record = readExactDataRecord(valueArg, personKeys);
896
+ return record === null
897
+ ? [`${pathArg} must use its exact schema`]
898
+ : [
899
+ ...validateBoundedString(record.subject, `${pathArg} subject`, cloudAccessContract.maximumSubjectLength),
900
+ ...validateOneOf(record.role, `${pathArg} role`, cloudAccessPersonRoles),
901
+ ];
902
+ };
903
+
904
+ const validatePeopleMap = (valueArg: unknown, pathArg: string): string[] => {
905
+ const record = readExactDataRecord(valueArg, peopleKeys);
906
+ if (record === null) {
907
+ return [`${pathArg} must use its exact schema`];
908
+ }
909
+ const errors = validateControllerOrigin(record.issuer, `${pathArg} issuer`,
910
+ controllerPeerSetContract.maximumOriginLength);
911
+ const { elements, errors: listErrors } = readList(record.entries, `${pathArg} entries`,
912
+ cloudAccessContract.maximumPeople, 'people');
913
+ errors.push(...listErrors);
914
+ if (elements !== null) {
915
+ elements.forEach((elementArg, indexArg) => {
916
+ errors.push(...validatePerson(elementArg, `${pathArg} entries[${indexArg}]`));
917
+ });
918
+ errors.push(...validateUnique(elements.map((elementArg) => readExactDataRecord(elementArg, personKeys)?.subject),
919
+ `${pathArg} entries`, 'subject'));
920
+ }
921
+ return errors;
922
+ };
923
+
924
+ /**
925
+ * The size of a report as the bound reads it: the UTF-8 bytes of its JSON. Call it on a report that
926
+ * passed the rest of `validateCloudAccessReport`, which calls it last.
927
+ */
928
+ export const measureCloudAccessReportBytes = (reportArg: ICloudAccessReport): number => (
929
+ new TextEncoder().encode(JSON.stringify(reportArg)).length
930
+ );
931
+
932
+ /**
933
+ * Validates one report and names every reason it is refused: exact keys, closed lists, each list's
934
+ * and each string's bound, and last the whole report's `cloudAccessContract.maximumReportBytes`.
935
+ * Cloud access answers `report-too-large` when the size is the reason and `request-invalid`
936
+ * otherwise. Cloudly runs it before it sends.
937
+ */
938
+ export const validateCloudAccessReport = (valueArg: unknown, pathArg = 'cloud access report'): string[] => {
939
+ const record = readExactDataRecord(valueArg, reportKeys);
940
+ if (record === null) {
941
+ return [`${pathArg} must use its exact schema`];
942
+ }
943
+ const errors = [
944
+ ...validateBoolean(record.healthy, `${pathArg} healthy`),
945
+ ...validateCounts(record.counts, `${pathArg} counts`),
946
+ ...validateNullable(record.people, `${pathArg} people`, validatePeopleMap),
947
+ ];
948
+ const versions = readList(record.versions, `${pathArg} versions`, cloudAccessContract.maximumVersions, 'versions');
949
+ errors.push(...versions.errors);
950
+ if (versions.elements !== null) {
951
+ versions.elements.forEach((elementArg, indexArg) => {
952
+ errors.push(...validateVersion(elementArg, `${pathArg} versions[${indexArg}]`));
953
+ });
954
+ // A repeated (product, running) would split its count; the pair is judged as one JSON token.
955
+ errors.push(...validateUnique(versions.elements.map((elementArg) => {
956
+ const version = readExactDataRecord(elementArg, versionKeys);
957
+ return typeof version?.product === 'string' && typeof version.running === 'string'
958
+ ? JSON.stringify([version.product, version.running])
959
+ : undefined;
960
+ }), `${pathArg} versions`, '(product, running)'));
961
+ }
962
+ const locations = readList(record.locations, `${pathArg} locations`, cloudAccessContract.maximumLocations,
963
+ 'locations');
964
+ errors.push(...locations.errors);
965
+ if (locations.elements !== null) {
966
+ locations.elements.forEach((elementArg, indexArg) => {
967
+ errors.push(...validateLocation(elementArg, `${pathArg} locations[${indexArg}]`));
968
+ });
969
+ errors.push(...validateUnique(
970
+ locations.elements.map((elementArg) => readExactDataRecord(elementArg, locationKeys)?.name),
971
+ `${pathArg} locations`, 'location'));
972
+ }
973
+ const attention = readList(record.attention, `${pathArg} attention`, cloudAccessContract.maximumAttentionItems,
974
+ 'items');
975
+ errors.push(...attention.errors);
976
+ if (attention.elements !== null) {
977
+ attention.elements.forEach((elementArg, indexArg) => {
978
+ errors.push(...validateAttentionItem(elementArg, `${pathArg} attention[${indexArg}]`));
979
+ });
980
+ errors.push(...validateUnique(
981
+ attention.elements.map((elementArg) => readExactDataRecord(elementArg, attentionKeys)?.key),
982
+ `${pathArg} attention`, 'key'));
983
+ }
984
+ if (errors.length === 0
985
+ && measureCloudAccessReportBytes(valueArg as ICloudAccessReport) > cloudAccessContract.maximumReportBytes) {
986
+ errors.push(`${pathArg} must be at most ${cloudAccessContract.maximumReportBytes} bytes as JSON`);
987
+ }
988
+ return errors;
989
+ };
990
+
991
+ const nameCheckKeyList = ['state', 'checkedAt', 'detail'] as const;
992
+ const nameCheckKeys: TCompleteKeyList<ICloudAccessNameCheck, typeof nameCheckKeyList> = nameCheckKeyList;
993
+ const checksKeyList = ['txt', 'address', 'caa'] as const;
994
+ const checksKeys: TCompleteKeyList<ICloudAccessBindingState['checks'], typeof checksKeyList> = checksKeyList;
995
+ const dnsRecordKeyList = ['type', 'name', 'value'] as const;
996
+ const dnsRecordKeys: TCompleteKeyList<ICloudAccessDnsRecord, typeof dnsRecordKeyList> = dnsRecordKeyList;
997
+ const bindingStateKeyList = [
998
+ 'bindingId', 'organizationId', 'organizationName', 'hostname', 'checks', 'pointsAtRelay', 'routed', 'records',
999
+ ] as const;
1000
+ const bindingStateKeys: TCompleteKeyList<ICloudAccessBindingState, typeof bindingStateKeyList> =
1001
+ bindingStateKeyList;
1002
+ const bindingStateRequestKeyList = ['recheck'] as const;
1003
+ const bindingStateRequestKeys: TCompleteKeyList<IGetCloudAccessBindingStateRequest, typeof bindingStateRequestKeyList> =
1004
+ bindingStateRequestKeyList;
1005
+
1006
+ const validateCheckDetail = (valueArg: unknown, pathArg: string): string[] => (
1007
+ validateBoundedString(valueArg, pathArg, cloudAccessContract.maximumCheckDetailLength)
1008
+ );
1009
+
1010
+ const validateNameCheck = (valueArg: unknown, pathArg: string): string[] => {
1011
+ const record = readExactDataRecord(valueArg, nameCheckKeys);
1012
+ if (record === null) {
1013
+ return [`${pathArg} must use its exact schema`];
1014
+ }
1015
+ const errors = [
1016
+ ...validateOneOf(record.state, `${pathArg} state`, cloudAccessNameCheckStates),
1017
+ ...validateNullable(record.detail, `${pathArg} detail`, validateCheckDetail),
1018
+ ];
1019
+ if (record.state === 'unchecked') {
1020
+ if (record.checkedAt !== null) {
1021
+ errors.push(`${pathArg} checkedAt must be null while unchecked`);
1022
+ }
1023
+ } else {
1024
+ errors.push(...validateUnixMilliseconds(record.checkedAt, `${pathArg} checkedAt`));
1025
+ }
1026
+ if (record.state === 'passing' && record.detail !== null) {
1027
+ errors.push(`${pathArg} detail must be null for a passing check`);
1028
+ }
1029
+ return errors;
1030
+ };
1031
+
1032
+ const validateDnsRecord = (valueArg: unknown, pathArg: string): string[] => {
1033
+ const record = readExactDataRecord(valueArg, dnsRecordKeys);
1034
+ if (record === null) {
1035
+ return [`${pathArg} must use its exact schema`];
1036
+ }
1037
+ return [
1038
+ ...validateOneOf(record.type, `${pathArg} type`, cloudAccessDnsRecordTypes),
1039
+ ...(typeof record.name === 'string' && record.name.length <= cloudAccessContract.maximumHostnameLength
1040
+ && isCloudAccessHostname(record.name.replace(/^_[a-z0-9-]+\./, ''))
1041
+ ? []
1042
+ : [`${pathArg} name must be a lowercase DNS name, optionally below one underscore label`]),
1043
+ ...validateBoundedString(record.value, `${pathArg} value`, cloudAccessContract.maximumDnsRecordValueLength),
1044
+ ];
1045
+ };
1046
+
1047
+ /**
1048
+ * Validates what `getCloudAccessBindingState` answers; Cloudly checks it before it shows it. A
1049
+ * routed binding has no failing and no unchecked check (a `lookup-error` keeps the previous verdict
1050
+ * for its grace).
1051
+ */
1052
+ export const validateCloudAccessBindingState = (
1053
+ valueArg: unknown,
1054
+ pathArg = 'cloud access binding state',
1055
+ ): string[] => {
1056
+ const record = readExactDataRecord(valueArg, bindingStateKeys);
1057
+ if (record === null) {
1058
+ return [`${pathArg} must use its exact schema`];
1059
+ }
1060
+ const errors = [
1061
+ ...validateRandomId(record.bindingId, `${pathArg} bindingId`),
1062
+ ...validateBoundedString(record.organizationId, `${pathArg} organizationId`,
1063
+ cloudAccessContract.maximumOrganizationIdLength),
1064
+ ...validateBoundedString(record.organizationName, `${pathArg} organizationName`,
1065
+ cloudAccessContract.maximumNameLength),
1066
+ ...validateHostname(record.hostname, `${pathArg} hostname`),
1067
+ ...validateNullable(record.pointsAtRelay, `${pathArg} pointsAtRelay`, validateBoolean),
1068
+ ...validateBoolean(record.routed, `${pathArg} routed`),
1069
+ ];
1070
+ const checks = readExactDataRecord(record.checks, checksKeys);
1071
+ if (checks === null) {
1072
+ errors.push(`${pathArg} checks must use its exact schema`);
1073
+ } else {
1074
+ for (const key of checksKeyList) {
1075
+ errors.push(...validateNameCheck(checks[key], `${pathArg} checks ${key}`));
1076
+ }
1077
+ const states = checksKeyList.map((keyArg) => readExactDataRecord(checks[keyArg], nameCheckKeys)?.state);
1078
+ if (record.routed === true && states.some((stateArg) => stateArg === 'failing' || stateArg === 'unchecked')) {
1079
+ errors.push(`${pathArg} routed must be false while a check is failing or unchecked`);
1080
+ }
1081
+ }
1082
+ const records = readList(record.records, `${pathArg} records`, cloudAccessContract.maximumDnsRecords, 'records');
1083
+ errors.push(...records.errors);
1084
+ if (records.elements !== null) {
1085
+ if (records.elements.length === 0) {
1086
+ errors.push(`${pathArg} records must name at least one record`);
1087
+ }
1088
+ records.elements.forEach((elementArg, indexArg) => {
1089
+ errors.push(...validateDnsRecord(elementArg, `${pathArg} records[${indexArg}]`));
1090
+ });
1091
+ }
1092
+ return errors;
1093
+ };
1094
+
1095
+ /** Validates a `getCloudAccessBindingState` body. */
1096
+ export const validateGetCloudAccessBindingStateRequest = (
1097
+ valueArg: unknown,
1098
+ pathArg = 'get cloud access binding state request',
1099
+ ): string[] => {
1100
+ const record = readExactDataRecord(valueArg, bindingStateRequestKeys);
1101
+ return record === null
1102
+ ? [`${pathArg} must use its exact schema`]
1103
+ : validateBoolean(record.recheck, `${pathArg} recheck`);
1104
+ };
1105
+
1106
+ const openStreamKeyList = ['streamId', 'token', 'clientAddress'] as const;
1107
+ const openStreamKeys: TCompleteKeyList<IOpenCloudAccessStreamRequest, typeof openStreamKeyList> =
1108
+ openStreamKeyList;
1109
+
1110
+ /** IPv4-mapped IPv6 (`::ffff:0:0/96`): a plain IPv4 address states itself as IPv4. */
1111
+ const ipv4MappedNetwork = 0xffffn;
1112
+
1113
+ /**
1114
+ * Validates an `openCloudAccessStream` body; Cloudly runs it before it dials. Exactly these three
1115
+ * members: a request that names a target, or anything else, is refused. No refusal carries the token.
1116
+ */
1117
+ export const validateOpenCloudAccessStreamRequest = (
1118
+ valueArg: unknown,
1119
+ pathArg = 'open cloud access stream request',
1120
+ ): string[] => {
1121
+ const record = readExactDataRecord(valueArg, openStreamKeys);
1122
+ if (record === null) {
1123
+ return [`${pathArg} must use its exact schema`];
1124
+ }
1125
+ const address = parseCanonicalIpAddress(record.clientAddress);
1126
+ return [
1127
+ ...validateRandomId(record.streamId, `${pathArg} streamId`),
1128
+ ...validateBase64url32(record.token, `${pathArg} token`),
1129
+ ...(address !== null && !(address.family === 6 && address.value >> 32n === ipv4MappedNetwork)
1130
+ ? []
1131
+ : [`${pathArg} clientAddress must be one canonical IPv4 or IPv6 address, never IPv4-mapped`]),
1132
+ ];
1133
+ };