@serve.zone/interfaces 32.75.0 → 32.77.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 (50) hide show
  1. package/changelog.md +22 -0
  2. package/dist_ts/00_commitinfo_data.js +1 -1
  3. package/dist_ts/data/backup.d.ts +3 -1
  4. package/dist_ts/data/backup.js +1 -1
  5. package/dist_ts/data/controller.d.ts +92 -0
  6. package/dist_ts/data/controller.js +138 -0
  7. package/dist_ts/data/gatewayconnector.d.ts +347 -0
  8. package/dist_ts/data/gatewayconnector.js +594 -0
  9. package/dist_ts/data/index.d.ts +2 -0
  10. package/dist_ts/data/index.js +3 -1
  11. package/dist_ts/data/location.d.ts +3 -1
  12. package/dist_ts/data/location.js +7 -5
  13. package/dist_ts/data/user.d.ts +8 -2
  14. package/dist_ts/private/controllercontract.d.ts +10 -0
  15. package/dist_ts/private/controllercontract.js +64 -0
  16. package/dist_ts/private/gatewayclientid.d.ts +6 -0
  17. package/dist_ts/private/gatewayclientid.js +11 -0
  18. package/dist_ts/requests/baremetal.d.ts +2 -1
  19. package/dist_ts/requests/cluster.d.ts +5 -3
  20. package/dist_ts/requests/gateway.d.ts +20 -3
  21. package/dist_ts/requests/gatewayconnector.d.ts +142 -0
  22. package/dist_ts/requests/gatewayconnector.js +2 -0
  23. package/dist_ts/requests/index.d.ts +2 -1
  24. package/dist_ts/requests/index.js +3 -2
  25. package/dist_ts/requests/node.d.ts +4 -1
  26. package/dist_ts/requests/settings.js +3 -5
  27. package/dist_ts/runtime.corestore.database.d.ts +23 -0
  28. package/dist_ts/runtime.corestore.database.js +41 -0
  29. package/dist_ts/runtime.d.ts +1 -0
  30. package/dist_ts/runtime.js +2 -1
  31. package/package.json +2 -2
  32. package/readme.md +146 -5
  33. package/ts/00_commitinfo_data.ts +1 -1
  34. package/ts/data/backup.ts +3 -1
  35. package/ts/data/controller.ts +218 -0
  36. package/ts/data/gatewayconnector.ts +955 -0
  37. package/ts/data/index.ts +2 -0
  38. package/ts/data/location.ts +6 -4
  39. package/ts/data/user.ts +8 -2
  40. package/ts/private/controllercontract.ts +74 -0
  41. package/ts/private/gatewayclientid.ts +13 -0
  42. package/ts/requests/baremetal.ts +2 -1
  43. package/ts/requests/cluster.ts +5 -3
  44. package/ts/requests/gateway.ts +20 -3
  45. package/ts/requests/gatewayconnector.ts +179 -0
  46. package/ts/requests/index.ts +2 -0
  47. package/ts/requests/node.ts +4 -1
  48. package/ts/requests/settings.ts +2 -4
  49. package/ts/runtime.corestore.database.ts +64 -0
  50. package/ts/runtime.ts +1 -0
@@ -0,0 +1,955 @@
1
+ import {
2
+ canonicalizeStrictJson,
3
+ createCanonicalJsonSha256Hex,
4
+ } from '../private/canonicaljson.js';
5
+ import {
6
+ validateControllerCounter,
7
+ validateControllerIdentifier,
8
+ validateControllerNonNegativeInteger,
9
+ validateControllerStrictJson,
10
+ } from '../private/controllercontract.js';
11
+ import { readDataElements, readDataProperty, readExactDataRecord } from '../private/dataproperties.js';
12
+ import { ipv4PrefixOfMapped, parseCanonicalIpAddress } from '../private/ipaddress.js';
13
+ import type { TCompleteKeyList } from '../private/keylist.js';
14
+ import { networkDigest } from '../private/networkcontract.js';
15
+ import { isCanonicalTokenList } from '../private/tokenlist.js';
16
+ import { isGatewayClientIdText } from '../private/gatewayclientid.js';
17
+ import { clusterIngressLimits, validateClusterRouteSourceAllowList } from './clusteringress.js';
18
+ import { type IControllerPeerSet, validateControllerPeerSet } from './controller.js';
19
+ import type { TSha256Digest } from './immutableimage.js';
20
+ import { isLocationName } from './location.js';
21
+ import { isReleaseVersion } from './releaseversion.js';
22
+ import { externalGatewayBootstrapContract } from './settings.js';
23
+
24
+ /*
25
+ * The gateway connector (AGL-1182): a gateway (dcrouter) dials its controller (Cloudly) on the
26
+ * controller's typedsocket server, authenticates with `registerCloudlyClientSession` as the machine
27
+ * identity it received at adoption, and then says hello with `registerGatewaySession`. Nothing
28
+ * dials an adopted gateway. Over that socket the controller pushes the whole desired state of the
29
+ * gateway's controller-owned areas, the gateway applies it area by area and reports what it
30
+ * applied in its status document. A gateway that cannot reach its controller serves the state it
31
+ * applied last.
32
+ */
33
+
34
+ /**
35
+ * Every configuration area of a gateway, in the one order a gateway applies a desired state's
36
+ * areas in. Each area is one whole table with exactly one owner per gateway: the gateway itself or
37
+ * its controller.
38
+ */
39
+ export const gatewayConfigAreaApplyOrder = Object.freeze([
40
+ 'security', 'dns', 'routes', 'mail', 'edges',
41
+ ] as const);
42
+
43
+ /** One configuration area of a gateway. */
44
+ export type TGatewayConfigArea = typeof gatewayConfigAreaApplyOrder[number];
45
+
46
+ /** True for one of `gatewayConfigAreaApplyOrder`. */
47
+ export const isGatewayConfigArea = (valueArg: unknown): valueArg is TGatewayConfigArea => (
48
+ (gatewayConfigAreaApplyOrder as readonly unknown[]).includes(valueArg)
49
+ );
50
+
51
+ export const gatewayConnectorContract = Object.freeze({
52
+ /** The digest domain of `computeGatewayAreaTableDigest`. */
53
+ areaTableDigestDomain: 'serve.zone/gateway-area-table',
54
+ /** A gateway pushes its status document at most once in this many milliseconds. */
55
+ minimumStatusPushIntervalMs: 5_000,
56
+ /** Each of `publicIps`, `proxyIps` and `forwardSourceAddresses`. */
57
+ maximumAddresses: 64,
58
+ /** Ranges per transport in `IGatewayStatusDocument.listeningPorts`; a range of any width counts once. */
59
+ maximumListeningPortRanges: 1024,
60
+ maximumDnsZones: 1024,
61
+ maximumHostnameLength: 253,
62
+ maximumRefusalDetailLength: 1024,
63
+ maximumStorageBackendLength: 64,
64
+ maximumStoragePathLength: 4096,
65
+ } as const);
66
+
67
+ /**
68
+ * True for a gateway name: the location name rule (`isLocationName`), one lowercase RFC 1123 label
69
+ * of 1 to 63 characters. A controller keeps each name on one of its gateways.
70
+ */
71
+ export const isGatewayName = (valueArg: unknown): valueArg is string => isLocationName(valueArg);
72
+
73
+ /**
74
+ * One gateway as its controller records it (`validateGateway`).
75
+ *
76
+ * `connection` says how the two reach each other. A `legacy` gateway is the dcrouter the
77
+ * controller still dials at its URL as the named gateway client. An `adopted` gateway dials the
78
+ * controller and is never dialled, so it carries no URL.
79
+ *
80
+ * The controller gateway is the one gateway whose gateway client the controller's own
81
+ * gateway-client calls (`requests.gateway`, `requests.mail` and `requests.webpush` under control
82
+ * auth) are bound to: a `legacy` gateway by its `gatewayClientId`, an `adopted` one by a non-null
83
+ * `controllerGatewayClientId`. A controller holds at most one.
84
+ */
85
+ export interface IGateway {
86
+ id: string;
87
+ /** Unique among the controller's gateways; `isGatewayName`. */
88
+ name: string;
89
+ /** The location the gateway stands in (`data.ILocation`); every gateway stands in one. */
90
+ locationId: string;
91
+ /**
92
+ * The sources the gateway's forwarded connections arrive from at a node, as canonical address
93
+ * prefixes (`192.0.2.10/32`) under the rules of `validateClusterRouteSourceAllowList`; empty when
94
+ * none is known. A cluster ingress admits a non-public hostname only from the union of every
95
+ * gateway's prefixes. The plain addresses a gateway states (`IGatewayAdoptionFacts`,
96
+ * `IGatewayStatusDocument` `forwardSourceAddresses`) become host prefixes here: `/32` for IPv4,
97
+ * `/128` for IPv6.
98
+ */
99
+ forwardSourcePrefixes: string[];
100
+ connection:
101
+ | {
102
+ kind: 'legacy';
103
+ /**
104
+ * The dcrouter URL the controller dials: an absolute `http` or `https` URL in its canonical
105
+ * spelling, without userinfo, query, fragment or trailing slash.
106
+ */
107
+ url: string;
108
+ /** The gateway client the controller's calls run as. */
109
+ gatewayClientId: string;
110
+ }
111
+ | {
112
+ kind: 'adopted';
113
+ /** Unix milliseconds on the controller's clock. */
114
+ adoptedAt: number;
115
+ /** The machine identity the gateway authenticates as. */
116
+ machineUserId: string;
117
+ /** Raised by every re-adoption; the previous generation is dead from then on. */
118
+ credentialGeneration: number;
119
+ /**
120
+ * The one gateway client the controller's gateway-client calls are bound to over the
121
+ * connector socket.
122
+ *
123
+ * - A `new` adoption binds `null`; the gateway then refuses those calls
124
+ * `gateway-client-unbound`.
125
+ * - An `existing` re-adoption of a legacy gateway moves its `gatewayClientId` into this field.
126
+ * - A re-adoption of an already adopted gateway keeps this field unchanged, `null` included.
127
+ * - No operation changes a non-null binding to another value.
128
+ */
129
+ controllerGatewayClientId: string | null;
130
+ };
131
+ }
132
+
133
+ /** What a gateway states about itself when it is adopted (`adoptGateway`). */
134
+ export interface IGatewayAdoptionFacts {
135
+ /** The dcrouter release the gateway runs (`data.isReleaseVersion`). */
136
+ dcrouterVersion: string;
137
+ /** The release of this package the gateway speaks (`data.isReleaseVersion`). */
138
+ interfacesVersion: string;
139
+ /** The host name of the gateway's machine: dot-separated RFC 1123 labels. */
140
+ hostname: string;
141
+ /** Canonical IPv4 or IPv6 addresses, each at most once. */
142
+ publicIps: string[];
143
+ /** Canonical IPv4 or IPv6 addresses, each at most once. */
144
+ proxyIps: string[];
145
+ /** Canonical IPv4 or IPv6 addresses, each at most once. */
146
+ forwardSourceAddresses: string[];
147
+ /**
148
+ * The areas this gateway can take from a controller, as a canonical token list (sorted by
149
+ * `compareWireTokens`, each once). A controller never pushes an area the gateway does not name.
150
+ */
151
+ controllerAreas: TGatewayConfigArea[];
152
+ }
153
+
154
+ /** One whole area table of a desired state. */
155
+ export interface IGatewayAreaTable {
156
+ area: TGatewayConfigArea;
157
+ /** `computeGatewayAreaTableDigest(area, content)`. */
158
+ digest: TSha256Digest;
159
+ /**
160
+ * The whole table, strict canonical JSON. Untyped in this contract: each area's content type and
161
+ * validator ship with the release that moves that area to the controller.
162
+ */
163
+ content: unknown;
164
+ /**
165
+ * Set on the push that moves the area from the gateway to the controller: the digest
166
+ * `exportGatewayArea` answered. The gateway applies it only while its local table still has that
167
+ * digest and refuses `local-changed-since-export` otherwise. `null` on every other push.
168
+ */
169
+ takeover: { localDigest: TSha256Digest } | null;
170
+ }
171
+
172
+ /**
173
+ * The whole desired state a controller pushes to one gateway (`applyDesiredState`).
174
+ *
175
+ * Documents are ordered by `(epoch, revision)` (`data.compareControllerRevisionOrder`): a newer one
176
+ * is applied, an equal one is an idempotent replay answered with the stored report, and an older
177
+ * one is refused `desired-state-stale` (`gatewayConnectorRefusals`).
178
+ */
179
+ export interface IGatewayDesiredState {
180
+ gatewayId: string;
181
+ controllerId: string;
182
+ epoch: number;
183
+ revision: number;
184
+ /** One table per controller-owned area, each area at most once. */
185
+ areas: IGatewayAreaTable[];
186
+ }
187
+
188
+ /**
189
+ * Every reason one side of the gateway connector answers instead of a request. The controller
190
+ * answers them instead of `adoptGateway`, `registerGatewaySession`, `pushGatewayStatus` and
191
+ * `createGatewayAdoptionCode`, and instead of a legacy gateway setting it no longer owns. The
192
+ * gateway answers them instead of a whole `applyDesiredState` document, an `exportGatewayArea`, a
193
+ * gateway-client call on the connector socket, or an HTTP call authenticated with a token of its
194
+ * controller-bound gateway client.
195
+ *
196
+ * Each is answered as a `TypedResponseError` whose `errorData` is
197
+ * `IGatewayConnectorRefusalErrorData` and whose text carries the detail, so a peer acts on the code
198
+ * without reading prose. A refusal of one area inside an applied document is none of these: the
199
+ * gateway reports it per area (`gatewayApplyRefusals`). An adoption code that names no location is
200
+ * refused `location-not-found` from `locationRefusals`.
201
+ */
202
+ export const gatewayConnectorRefusals = Object.freeze([
203
+ /** No adoption code has the value the gateway redeemed. */
204
+ 'adoption-code-unknown',
205
+ /** The adoption code's lifetime ended before the gateway redeemed it. */
206
+ 'adoption-code-expired',
207
+ /** The adoption code was redeemed already; a code adopts once. */
208
+ 'adoption-code-used',
209
+ /** A code for a new gateway names a name another gateway of this controller carries. */
210
+ 'gateway-name-taken',
211
+ /** A code for an existing gateway, or a gateway identity, names no gateway the controller records. */
212
+ 'gateway-not-found',
213
+ /** The controller's public origin is not a canonical `https` origin, so no gateway can adopt it. */
214
+ 'controller-origin-invalid',
215
+ /** The socket authenticated with a gateway credential generation a re-adoption has replaced. */
216
+ 'credential-generation-stale',
217
+ /** A hello whose `registrationSequence` does not exceed the one the same socket sent before. */
218
+ 'registration-sequence-not-advancing',
219
+ /**
220
+ * The peer belongs to another controller: a hello whose `known.controllerId` names another
221
+ * controller, or a desired state whose `controllerId` is not the controller that adopted the
222
+ * gateway. Nothing is pushed or applied.
223
+ */
224
+ 'controller-mismatch',
225
+ /** A hello whose `known.epoch` is above this controller's epoch. Nothing is pushed. */
226
+ 'controller-epoch-ahead',
227
+ /** A gateway call on a socket that has no accepted `registerGatewaySession`. */
228
+ 'gateway-session-required',
229
+ /**
230
+ * A status push sooner than `gatewayConnectorContract.minimumStatusPushIntervalMs` after the last
231
+ * accepted one. The gateway sends its newest document again once the interval has passed.
232
+ */
233
+ 'status-too-frequent',
234
+ /**
235
+ * The controller gateway is adopted. The controller answers it to an edit of the legacy gateway
236
+ * URL or client id setting and to the legacy gateway credential bootstrap, which no longer apply.
237
+ * The gateway answers it to any HTTP call with a token of its controller-bound gateway client
238
+ * (`controllerGatewayClientId`): that client is served on the connector socket only.
239
+ */
240
+ 'controller-gateway-adopted',
241
+ /**
242
+ * The request failed its contract validator (`validateGatewayDesiredState` for a desired state);
243
+ * the error text carries the validator's sentences.
244
+ */
245
+ 'request-invalid',
246
+ /**
247
+ * A desired state older by `(epoch, revision)` than the one the gateway applied; the error text
248
+ * names the applied epoch and revision. An equal one is no refusal: the gateway answers it with
249
+ * the stored report.
250
+ */
251
+ 'desired-state-stale',
252
+ /** A desired state whose `gatewayId` is not the gateway's own. Nothing is applied. */
253
+ 'gateway-mismatch',
254
+ /**
255
+ * An `exportGatewayArea` for an area the gateway does not take from a controller
256
+ * (`controllerAreas`); the same meaning as the per-area refusal of that name.
257
+ */
258
+ 'unsupported-area',
259
+ /**
260
+ * A gateway-client call on the connector socket of a gateway adopted without a controller binding
261
+ * (`controllerGatewayClientId: null`).
262
+ */
263
+ 'gateway-client-unbound',
264
+ ] as const);
265
+
266
+ /** One of the reasons one side of the gateway connector answers instead of a request. */
267
+ export type TGatewayConnectorRefusal = typeof gatewayConnectorRefusals[number];
268
+
269
+ /** A connector refusal as `TypedResponseError.errorData`; the error text carries its detail. */
270
+ export interface IGatewayConnectorRefusalErrorData {
271
+ code: TGatewayConnectorRefusal;
272
+ /** Never: the same request is refused again until the state the code names has changed. */
273
+ retryable: false;
274
+ }
275
+
276
+ /** True for one of `gatewayConnectorRefusals`. */
277
+ export const isGatewayConnectorRefusal = (valueArg: unknown): valueArg is TGatewayConnectorRefusal => (
278
+ (gatewayConnectorRefusals as readonly unknown[]).includes(valueArg)
279
+ );
280
+
281
+ /**
282
+ * Every reason a gateway refuses an area of a desired state it accepted as a whole. Each is
283
+ * reported per area in `IGatewayAreaApplyState.refusal`. A refusal of the whole document (stale,
284
+ * from another controller, for another gateway, invalid) is answered on the request instead
285
+ * (`gatewayConnectorRefusals`) and never stored in a report.
286
+ */
287
+ export const gatewayApplyRefusals = Object.freeze([
288
+ /** A table failed validation; a gateway validates every table first and then applies none. */
289
+ 'invalid-table',
290
+ /** The document carries an area the gateway does not take from a controller (`controllerAreas`). */
291
+ 'unsupported-area',
292
+ /** A takeover's `localDigest` is no longer the digest of the gateway's local table. */
293
+ 'local-changed-since-export',
294
+ /** Applying a valid table failed; this area and every later one keep their previous tables. */
295
+ 'apply-failed',
296
+ ] as const);
297
+
298
+ /** One of the reasons a gateway refuses an area of a desired state. */
299
+ export type TGatewayApplyRefusal = typeof gatewayApplyRefusals[number];
300
+
301
+ /** True for one of `gatewayApplyRefusals`. */
302
+ export const isGatewayApplyRefusal = (valueArg: unknown): valueArg is TGatewayApplyRefusal => (
303
+ (gatewayApplyRefusals as readonly unknown[]).includes(valueArg)
304
+ );
305
+
306
+ /** Where one area of one gateway stands after the last desired state it received. */
307
+ export interface IGatewayAreaApplyState {
308
+ area: TGatewayConfigArea;
309
+ /** Who writes the area on this gateway. It moves to `controller` once and never back. */
310
+ owner: 'gateway' | 'controller';
311
+ /** The digest of the table the gateway serves for the area; `null` while it serves none. */
312
+ digest: TSha256Digest | null;
313
+ /** The controller revision of that table; `null` for a table no controller pushed. */
314
+ revision: number | null;
315
+ /**
316
+ * `applied` with no refusal; `rejected` with the refusal; `not-attempted` for an area a gateway
317
+ * did not reach because an earlier area of the same document was refused.
318
+ */
319
+ state: 'applied' | 'rejected' | 'not-attempted';
320
+ refusal: { reason: TGatewayApplyRefusal; detail: string } | null;
321
+ }
322
+
323
+ /** What a gateway applied, as `applyDesiredState` answers and the status document carries it. */
324
+ export interface IGatewayApplyReport {
325
+ /** The epoch of the last document applied whole; `null` before the first. */
326
+ epoch: number | null;
327
+ /**
328
+ * The revision of the last document applied whole; `null` before the first. It advances only
329
+ * when every area of a document is applied, so a gateway applied revision N exactly when this is
330
+ * at least N.
331
+ */
332
+ appliedRevision: number | null;
333
+ /** Each area at most once. */
334
+ areas: IGatewayAreaApplyState[];
335
+ }
336
+
337
+ /**
338
+ * An inclusive range of ports a gateway listens on, as a route's `match.ports` states it
339
+ * (SmartProxy's `{ from, to }`); one port is `{ from: port, to: port }`.
340
+ */
341
+ export interface IGatewayPortRange {
342
+ /** 1 to 65535. */
343
+ from: number;
344
+ /** `from` to 65535. */
345
+ to: number;
346
+ }
347
+
348
+ /**
349
+ * Every port a gateway listens on, per socket transport; each list in the canonical range form:
350
+ * sorted by `from`, and each range starts at least two ports after the previous one ends, so ranges
351
+ * neither overlap nor touch (a gateway merges `{ 80, 80 }` and `{ 81, 81 }` into `{ 80, 81 }`), at
352
+ * most `gatewayConnectorContract.maximumListeningPortRanges` ranges per transport.
353
+ *
354
+ * A gateway reports every public socket it has open, not only its SmartProxy routes. dcrouter
355
+ * derives a route's transports as its inbound proxy listener keys do: `match.transport` `udp` is
356
+ * udp, `all` is both, `tcp` or absent is tcp. QUIC and HTTP/3 count under udp. Each transport is
357
+ * merged on its own, never across transports, so one port may appear in both lists.
358
+ */
359
+ export interface IGatewayListeningPorts {
360
+ tcp: IGatewayPortRange[];
361
+ udp: IGatewayPortRange[];
362
+ }
363
+
364
+ /**
365
+ * Everything a gateway reports about itself, in one document (`pushGatewayStatus`). It is also
366
+ * what the gateway's own status page and CLI read.
367
+ */
368
+ export interface IGatewayStatusDocument {
369
+ gatewayId: string;
370
+ /** `data.isReleaseVersion`. */
371
+ dcrouterVersion: string;
372
+ /** `data.isReleaseVersion`. */
373
+ interfacesVersion: string;
374
+ /** The controller the gateway stored. */
375
+ controller: IControllerPeerSet;
376
+ /** Unix milliseconds since the current controller connection; `null` while disconnected. */
377
+ connectedSince: number | null;
378
+ applied: IGatewayApplyReport;
379
+ /** Unix milliseconds of the last whole apply; `null` before the first. */
380
+ appliedAt: number | null;
381
+ publicIps: string[];
382
+ proxyIps: string[];
383
+ forwardSourceAddresses: string[];
384
+ /** Every port the gateway listens on, per transport (`IGatewayListeningPorts`). */
385
+ listeningPorts: IGatewayListeningPorts;
386
+ storage: { backend: string; path: string | null };
387
+ /** Each zone at most once. */
388
+ dnsZones: { zone: string; recordsServed: number }[];
389
+ }
390
+
391
+ /**
392
+ * The hello a gateway sends after `registerCloudlyClientSession` on its socket. The gateway is the
393
+ * one the verified machine identity names and is never a field here.
394
+ */
395
+ export interface IRegisterGatewaySessionRequest {
396
+ /**
397
+ * Counts up once per attempt within one gateway process and restarts at 0 with the process; a
398
+ * controller refuses one that does not advance.
399
+ */
400
+ registrationSequence: number;
401
+ /** `data.isReleaseVersion`. */
402
+ dcrouterVersion: string;
403
+ /** `data.isReleaseVersion`. */
404
+ interfacesVersion: string;
405
+ /** As in `IGatewayAdoptionFacts.controllerAreas`. */
406
+ controllerAreas: TGatewayConfigArea[];
407
+ /** The controller and epoch the gateway stored; `null` when it stored none. */
408
+ known: { controllerId: string; epoch: number } | null;
409
+ applied: IGatewayApplyReport;
410
+ }
411
+
412
+ /** One area table as the gateway holds it locally, as `exportGatewayArea` answers it. */
413
+ export interface IGatewayAreaExport {
414
+ area: TGatewayConfigArea;
415
+ /** `computeGatewayAreaTableDigest(area, content)`. */
416
+ digest: TSha256Digest;
417
+ content: unknown;
418
+ }
419
+
420
+ const failAreaTable = (reasonArg: string): never => {
421
+ throw new Error(`Gateway area table digest input rejected: ${reasonArg}.`);
422
+ };
423
+
424
+ /**
425
+ * The canonical JSON an area table digest hashes: the digest domain, the area and the whole
426
+ * content. Throws for an unknown area and for content that is not strict canonical JSON (safe
427
+ * integers only, no `undefined`, no cycle, no accessor).
428
+ */
429
+ export const createGatewayAreaTableDigestInput = (areaArg: TGatewayConfigArea, contentArg: unknown): string => {
430
+ if (!isGatewayConfigArea(areaArg)) {
431
+ failAreaTable('unknown area');
432
+ }
433
+ return canonicalizeStrictJson({
434
+ domain: gatewayConnectorContract.areaTableDigestDomain,
435
+ area: areaArg,
436
+ content: contentArg,
437
+ }, failAreaTable, 'gateway area table');
438
+ };
439
+
440
+ /**
441
+ * `sha256:<hex>` of `createGatewayAreaTableDigestInput`, through Web Crypto. The controller and the
442
+ * gateway digest a table with this one function, so an exported local table and the controller's
443
+ * compiled table of the same content have the same digest.
444
+ */
445
+ export const computeGatewayAreaTableDigest = async (
446
+ areaArg: TGatewayConfigArea,
447
+ contentArg: unknown,
448
+ ): Promise<TSha256Digest> => `sha256:${await createCanonicalJsonSha256Hex(
449
+ createGatewayAreaTableDigestInput(areaArg, contentArg), failAreaTable,
450
+ )}`;
451
+
452
+ const adoptionFactsKeyList = [
453
+ 'dcrouterVersion', 'interfacesVersion', 'hostname', 'publicIps', 'proxyIps', 'forwardSourceAddresses',
454
+ 'controllerAreas',
455
+ ] as const;
456
+ const adoptionFactsKeys: TCompleteKeyList<IGatewayAdoptionFacts, typeof adoptionFactsKeyList> = adoptionFactsKeyList;
457
+ const areaTableKeyList = ['area', 'digest', 'content', 'takeover'] as const;
458
+ const areaTableKeys: TCompleteKeyList<IGatewayAreaTable, typeof areaTableKeyList> = areaTableKeyList;
459
+ const desiredStateKeyList = ['gatewayId', 'controllerId', 'epoch', 'revision', 'areas'] as const;
460
+ const desiredStateKeys: TCompleteKeyList<IGatewayDesiredState, typeof desiredStateKeyList> = desiredStateKeyList;
461
+ const areaApplyStateKeyList = ['area', 'owner', 'digest', 'revision', 'state', 'refusal'] as const;
462
+ const areaApplyStateKeys: TCompleteKeyList<IGatewayAreaApplyState, typeof areaApplyStateKeyList> =
463
+ areaApplyStateKeyList;
464
+ const applyReportKeyList = ['epoch', 'appliedRevision', 'areas'] as const;
465
+ const applyReportKeys: TCompleteKeyList<IGatewayApplyReport, typeof applyReportKeyList> = applyReportKeyList;
466
+ const statusDocumentKeyList = [
467
+ 'gatewayId', 'dcrouterVersion', 'interfacesVersion', 'controller', 'connectedSince', 'applied', 'appliedAt',
468
+ 'publicIps', 'proxyIps', 'forwardSourceAddresses', 'listeningPorts', 'storage', 'dnsZones',
469
+ ] as const;
470
+ const statusDocumentKeys: TCompleteKeyList<IGatewayStatusDocument, typeof statusDocumentKeyList> =
471
+ statusDocumentKeyList;
472
+ const registerSessionKeyList = [
473
+ 'registrationSequence', 'dcrouterVersion', 'interfacesVersion', 'controllerAreas', 'known', 'applied',
474
+ ] as const;
475
+ const registerSessionKeys: TCompleteKeyList<IRegisterGatewaySessionRequest, typeof registerSessionKeyList> =
476
+ registerSessionKeyList;
477
+ const areaExportKeyList = ['area', 'digest', 'content'] as const;
478
+ const areaExportKeys: TCompleteKeyList<IGatewayAreaExport, typeof areaExportKeyList> = areaExportKeyList;
479
+ const gatewayKeyList = ['id', 'name', 'locationId', 'forwardSourcePrefixes', 'connection'] as const;
480
+ const gatewayKeys: TCompleteKeyList<IGateway, typeof gatewayKeyList> = gatewayKeyList;
481
+ type TLegacyGatewayConnection = Extract<IGateway['connection'], { kind: 'legacy' }>;
482
+ const legacyConnectionKeyList = ['kind', 'url', 'gatewayClientId'] as const;
483
+ const legacyConnectionKeys: TCompleteKeyList<TLegacyGatewayConnection, typeof legacyConnectionKeyList> =
484
+ legacyConnectionKeyList;
485
+ type TAdoptedGatewayConnection = Extract<IGateway['connection'], { kind: 'adopted' }>;
486
+ const adoptedConnectionKeyList = [
487
+ 'kind', 'adoptedAt', 'machineUserId', 'credentialGeneration', 'controllerGatewayClientId',
488
+ ] as const;
489
+ const adoptedConnectionKeys: TCompleteKeyList<TAdoptedGatewayConnection, typeof adoptedConnectionKeyList> =
490
+ adoptedConnectionKeyList;
491
+
492
+ const areaOwners: readonly IGatewayAreaApplyState['owner'][] = ['controller', 'gateway'];
493
+ const areaApplyStates: readonly IGatewayAreaApplyState['state'][] = ['applied', 'rejected', 'not-attempted'];
494
+ const hostnameLabel = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/;
495
+ const dnsZoneLabel = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
496
+
497
+ const validateArea = (valueArg: unknown, pathArg: string): string[] => (
498
+ isGatewayConfigArea(valueArg) ? [] : [`${pathArg} must be one of ${gatewayConfigAreaApplyOrder.join(', ')}`]
499
+ );
500
+
501
+ const validateDigest = (valueArg: unknown, pathArg: string): string[] => {
502
+ try {
503
+ networkDigest(valueArg);
504
+ return [];
505
+ } catch {
506
+ return [`${pathArg} must be sha256: followed by 64 lowercase hex digits`];
507
+ }
508
+ };
509
+
510
+ const validateNullable = (
511
+ valueArg: unknown,
512
+ pathArg: string,
513
+ validateArg: (valueArg: unknown, pathArg: string) => string[],
514
+ ): string[] => (valueArg === null ? [] : validateArg(valueArg, pathArg));
515
+
516
+ const validateVersion = (valueArg: unknown, pathArg: string): string[] => (
517
+ isReleaseVersion(valueArg) ? [] : [`${pathArg} must be a release version such as 1.2.3`]
518
+ );
519
+
520
+ const validateBoundedString = (valueArg: unknown, pathArg: string, maximumLengthArg: number): string[] => (
521
+ typeof valueArg === 'string' && valueArg.length > 0 && valueArg.length <= maximumLengthArg
522
+ ? []
523
+ : [`${pathArg} must be a string of 1 to ${maximumLengthArg} characters`]
524
+ );
525
+
526
+ const validateControllerAreas = (valueArg: unknown, pathArg: string): string[] => (
527
+ isCanonicalTokenList(valueArg, gatewayConfigAreaApplyOrder)
528
+ ? []
529
+ : [`${pathArg} must list areas of ${gatewayConfigAreaApplyOrder.join(', ')} sorted, each once`]
530
+ );
531
+
532
+ const validateAddresses = (valueArg: unknown, pathArg: string): string[] => {
533
+ const addresses = readDataElements(valueArg, gatewayConnectorContract.maximumAddresses);
534
+ if (addresses === null) {
535
+ return [`${pathArg} must be a dense list of at most ${gatewayConnectorContract.maximumAddresses} addresses`];
536
+ }
537
+ const errors = addresses.flatMap((addressArg, indexArg) => {
538
+ const address = parseCanonicalIpAddress(addressArg);
539
+ if (address === null) {
540
+ return [`${pathArg}[${indexArg}] must be a canonical IPv4 or IPv6 address`];
541
+ }
542
+ // An IPv4 source is stated as IPv4, so its host prefix is one the cluster allow-list admits.
543
+ return ipv4PrefixOfMapped({ family: address.family, network: address.value, length: 128 }) === null
544
+ ? []
545
+ : [`${pathArg}[${indexArg}] must not be IPv4-mapped; write the IPv4 address`];
546
+ });
547
+ if (new Set(addresses).size !== addresses.length) {
548
+ errors.push(`${pathArg} must name each address once`);
549
+ }
550
+ return errors;
551
+ };
552
+
553
+ /**
554
+ * A dense, bounded list whose every entry is validated and whose entries name each value of
555
+ * `keyArg` at most once. An entry that does not carry the key as data is refused by its own
556
+ * validator and left out of the repetition check.
557
+ */
558
+ const validateKeyedList = (
559
+ valueArg: unknown,
560
+ pathArg: string,
561
+ maximumLengthArg: number,
562
+ keyArg: string,
563
+ validateEntryArg: (valueArg: unknown, pathArg: string) => string[],
564
+ ): string[] => {
565
+ const entries = readDataElements(valueArg, maximumLengthArg);
566
+ if (entries === null) {
567
+ return [`${pathArg} must be a dense list of at most ${maximumLengthArg} entries`];
568
+ }
569
+ const errors = entries.flatMap((entryArg, indexArg) => validateEntryArg(entryArg, `${pathArg}[${indexArg}]`));
570
+ const keys = entries.flatMap((entryArg) => {
571
+ const property = readDataProperty(entryArg, keyArg);
572
+ return property === null ? [] : [property.value];
573
+ });
574
+ if (new Set(keys).size !== keys.length) {
575
+ errors.push(`${pathArg} must name each ${keyArg} once`);
576
+ }
577
+ return errors;
578
+ };
579
+
580
+ const validateAreaTable = (valueArg: unknown, pathArg: string): string[] => {
581
+ const record = readExactDataRecord(valueArg, areaTableKeys);
582
+ if (record === null) {
583
+ return [`${pathArg} must use its exact schema`];
584
+ }
585
+ const errors = [
586
+ ...validateArea(record.area, `${pathArg} area`),
587
+ ...validateDigest(record.digest, `${pathArg} digest`),
588
+ ...validateControllerStrictJson(record.content, `${pathArg} content`),
589
+ ];
590
+ if (record.takeover !== null) {
591
+ const takeover = readExactDataRecord(record.takeover, ['localDigest']);
592
+ errors.push(...(takeover === null
593
+ ? [`${pathArg} takeover must be null or use its exact schema`]
594
+ : validateDigest(takeover.localDigest, `${pathArg} takeover localDigest`)));
595
+ }
596
+ return errors;
597
+ };
598
+
599
+ /**
600
+ * Validates one desired state and names every reason it is refused.
601
+ *
602
+ * The envelope only: every table's digest has the digest form and its content is strict canonical
603
+ * JSON, but whether the digest is `computeGatewayAreaTableDigest` of the content, what the content
604
+ * of an area must hold, and how the document orders against the one applied are the gateway's to
605
+ * judge (`invalid-table`, `desired-state-stale`).
606
+ */
607
+ export const validateGatewayDesiredState = (
608
+ valueArg: unknown,
609
+ pathArg = 'gateway desired state',
610
+ ): string[] => {
611
+ const record = readExactDataRecord(valueArg, desiredStateKeys);
612
+ if (record === null) {
613
+ return [`${pathArg} must use its exact schema`];
614
+ }
615
+ return [
616
+ ...validateControllerIdentifier(record.gatewayId, `${pathArg} gatewayId`),
617
+ ...validateControllerIdentifier(record.controllerId, `${pathArg} controllerId`),
618
+ ...validateControllerCounter(record.epoch, `${pathArg} epoch`),
619
+ ...validateControllerCounter(record.revision, `${pathArg} revision`),
620
+ ...validateKeyedList(record.areas, `${pathArg} areas`, gatewayConfigAreaApplyOrder.length, 'area',
621
+ validateAreaTable),
622
+ ];
623
+ };
624
+
625
+ const validateAreaApplyState = (valueArg: unknown, pathArg: string): string[] => {
626
+ const record = readExactDataRecord(valueArg, areaApplyStateKeys);
627
+ if (record === null) {
628
+ return [`${pathArg} must use its exact schema`];
629
+ }
630
+ const errors = [
631
+ ...validateArea(record.area, `${pathArg} area`),
632
+ ...(areaOwners.some((ownerArg) => ownerArg === record.owner)
633
+ ? []
634
+ : [`${pathArg} owner must be one of ${areaOwners.join(', ')}`]),
635
+ ...validateNullable(record.digest, `${pathArg} digest`, validateDigest),
636
+ ...validateNullable(record.revision, `${pathArg} revision`, validateControllerCounter),
637
+ ];
638
+ if (!areaApplyStates.some((stateArg) => stateArg === record.state)) {
639
+ errors.push(`${pathArg} state must be one of ${areaApplyStates.join(', ')}`);
640
+ }
641
+ if (record.refusal === null) {
642
+ if (record.state === 'rejected') {
643
+ errors.push(`${pathArg} refusal must name why a rejected area was refused`);
644
+ }
645
+ return errors;
646
+ }
647
+ if (record.state === 'applied') {
648
+ errors.push(`${pathArg} refusal must be null for an applied area`);
649
+ }
650
+ const refusal = readExactDataRecord(record.refusal, ['reason', 'detail']);
651
+ if (refusal === null) {
652
+ errors.push(`${pathArg} refusal must be null or use its exact schema`);
653
+ return errors;
654
+ }
655
+ if (!isGatewayApplyRefusal(refusal.reason)) {
656
+ errors.push(`${pathArg} refusal reason must be one of ${gatewayApplyRefusals.join(', ')}`);
657
+ }
658
+ errors.push(...validateBoundedString(refusal.detail, `${pathArg} refusal detail`,
659
+ gatewayConnectorContract.maximumRefusalDetailLength));
660
+ return errors;
661
+ };
662
+
663
+ /** Validates one apply report and names every reason it is refused. */
664
+ export const validateGatewayApplyReport = (
665
+ valueArg: unknown,
666
+ pathArg = 'gateway apply report',
667
+ ): string[] => {
668
+ const record = readExactDataRecord(valueArg, applyReportKeys);
669
+ if (record === null) {
670
+ return [`${pathArg} must use its exact schema`];
671
+ }
672
+ return [
673
+ ...validateNullable(record.epoch, `${pathArg} epoch`, validateControllerCounter),
674
+ ...validateNullable(record.appliedRevision, `${pathArg} appliedRevision`, validateControllerCounter),
675
+ ...validateKeyedList(record.areas, `${pathArg} areas`, gatewayConfigAreaApplyOrder.length, 'area',
676
+ validateAreaApplyState),
677
+ ];
678
+ };
679
+
680
+ /** Validates the facts a gateway states at adoption and names every reason they are refused. */
681
+ export const validateGatewayAdoptionFacts = (
682
+ valueArg: unknown,
683
+ pathArg = 'gateway adoption facts',
684
+ ): string[] => {
685
+ const record = readExactDataRecord(valueArg, adoptionFactsKeys);
686
+ if (record === null) {
687
+ return [`${pathArg} must use its exact schema`];
688
+ }
689
+ const hostname = record.hostname;
690
+ return [
691
+ ...validateVersion(record.dcrouterVersion, `${pathArg} dcrouterVersion`),
692
+ ...validateVersion(record.interfacesVersion, `${pathArg} interfacesVersion`),
693
+ ...(typeof hostname === 'string'
694
+ && hostname.length <= gatewayConnectorContract.maximumHostnameLength
695
+ && hostname.split('.').every((labelArg) => hostnameLabel.test(labelArg))
696
+ ? []
697
+ : [`${pathArg} hostname must be at most ${gatewayConnectorContract.maximumHostnameLength} characters `
698
+ + 'of dot-separated RFC 1123 labels']),
699
+ ...validateAddresses(record.publicIps, `${pathArg} publicIps`),
700
+ ...validateAddresses(record.proxyIps, `${pathArg} proxyIps`),
701
+ ...validateAddresses(record.forwardSourceAddresses, `${pathArg} forwardSourceAddresses`),
702
+ ...validateControllerAreas(record.controllerAreas, `${pathArg} controllerAreas`),
703
+ ];
704
+ };
705
+
706
+ /** The range as data, or the reason it is refused. */
707
+ const readPortRange = (valueArg: unknown, pathArg: string): IGatewayPortRange | string => {
708
+ const record = readExactDataRecord(valueArg, ['from', 'to']);
709
+ if (record === null) {
710
+ return `${pathArg} must use its exact schema`;
711
+ }
712
+ const { from, to } = record;
713
+ return typeof from === 'number' && typeof to === 'number' && Number.isSafeInteger(from)
714
+ && Number.isSafeInteger(to) && from >= 1 && from <= to && to <= 65535
715
+ ? { from, to }
716
+ : `${pathArg} must be integers with 1 <= from <= to <= 65535`;
717
+ };
718
+
719
+ const validateListeningPorts = (valueArg: unknown, pathArg: string): string[] => {
720
+ const maximum = gatewayConnectorContract.maximumListeningPortRanges;
721
+ const elements = readDataElements(valueArg, maximum);
722
+ if (elements === null) {
723
+ return [`${pathArg} must be a dense list of at most ${maximum} port ranges`];
724
+ }
725
+ const ranges = elements.map((elementArg, indexArg) => readPortRange(elementArg, `${pathArg}[${indexArg}]`));
726
+ const errors = ranges.filter((rangeArg): rangeArg is string => typeof rangeArg === 'string');
727
+ if (errors.length > 0) {
728
+ return errors;
729
+ }
730
+ const valid = ranges.filter((rangeArg): rangeArg is IGatewayPortRange => typeof rangeArg !== 'string');
731
+ for (let index = 1; index < valid.length; index++) {
732
+ if (valid[index].from <= valid[index - 1].to + 1) {
733
+ errors.push(`${pathArg}[${index}] must start at least two ports after ${pathArg}[${index - 1}] ends `
734
+ + '(sorted by from, overlapping and touching ranges merged)');
735
+ }
736
+ }
737
+ return errors;
738
+ };
739
+
740
+ const validateListeningPortsPerTransport = (valueArg: unknown, pathArg: string): string[] => {
741
+ const record = readExactDataRecord(valueArg, ['tcp', 'udp']);
742
+ if (record === null) {
743
+ return [`${pathArg} must use its exact schema`];
744
+ }
745
+ return [
746
+ ...validateListeningPorts(record.tcp, `${pathArg}.tcp`),
747
+ ...validateListeningPorts(record.udp, `${pathArg}.udp`),
748
+ ];
749
+ };
750
+
751
+ const validateDnsZone = (valueArg: unknown, pathArg: string): string[] => {
752
+ const record = readExactDataRecord(valueArg, ['zone', 'recordsServed']);
753
+ if (record === null) {
754
+ return [`${pathArg} must use its exact schema`];
755
+ }
756
+ const zone = record.zone;
757
+ return [
758
+ ...(typeof zone === 'string'
759
+ && zone.length <= gatewayConnectorContract.maximumHostnameLength
760
+ && zone.split('.').every((labelArg) => dnsZoneLabel.test(labelArg))
761
+ ? []
762
+ : [`${pathArg} zone must be at most ${gatewayConnectorContract.maximumHostnameLength} characters `
763
+ + 'of dot-separated lowercase RFC 1123 labels']),
764
+ ...validateControllerNonNegativeInteger(record.recordsServed, `${pathArg} recordsServed`),
765
+ ];
766
+ };
767
+
768
+ /**
769
+ * Validates one status document and names every reason it is refused. A controller stores a
770
+ * status document only when this returns no errors.
771
+ */
772
+ export const validateGatewayStatusDocument = (
773
+ valueArg: unknown,
774
+ pathArg = 'gateway status document',
775
+ ): string[] => {
776
+ const record = readExactDataRecord(valueArg, statusDocumentKeys);
777
+ if (record === null) {
778
+ return [`${pathArg} must use its exact schema`];
779
+ }
780
+ const errors = [
781
+ ...validateControllerIdentifier(record.gatewayId, `${pathArg} gatewayId`),
782
+ ...validateVersion(record.dcrouterVersion, `${pathArg} dcrouterVersion`),
783
+ ...validateVersion(record.interfacesVersion, `${pathArg} interfacesVersion`),
784
+ ...validateControllerPeerSet(record.controller, `${pathArg} controller`),
785
+ ...validateNullable(record.connectedSince, `${pathArg} connectedSince`, validateControllerNonNegativeInteger),
786
+ ...validateGatewayApplyReport(record.applied, `${pathArg} applied`),
787
+ ...validateNullable(record.appliedAt, `${pathArg} appliedAt`, validateControllerNonNegativeInteger),
788
+ ...validateAddresses(record.publicIps, `${pathArg} publicIps`),
789
+ ...validateAddresses(record.proxyIps, `${pathArg} proxyIps`),
790
+ ...validateAddresses(record.forwardSourceAddresses, `${pathArg} forwardSourceAddresses`),
791
+ ...validateListeningPortsPerTransport(record.listeningPorts, `${pathArg} listeningPorts`),
792
+ ...validateKeyedList(record.dnsZones, `${pathArg} dnsZones`, gatewayConnectorContract.maximumDnsZones,
793
+ 'zone', validateDnsZone),
794
+ ];
795
+ const storage = readExactDataRecord(record.storage, ['backend', 'path']);
796
+ if (storage === null) {
797
+ errors.push(`${pathArg} storage must use its exact schema`);
798
+ return errors;
799
+ }
800
+ errors.push(...validateBoundedString(storage.backend, `${pathArg} storage backend`,
801
+ gatewayConnectorContract.maximumStorageBackendLength));
802
+ errors.push(...validateNullable(storage.path, `${pathArg} storage path`, (pathValueArg, fieldArg) => (
803
+ validateBoundedString(pathValueArg, fieldArg, gatewayConnectorContract.maximumStoragePathLength)
804
+ )));
805
+ return errors;
806
+ };
807
+
808
+ /**
809
+ * Validates one gateway session hello and names every reason it is refused.
810
+ *
811
+ * Shape only: whether the sequence advances, and whether `known` names this controller at an
812
+ * epoch it may hold, is the controller's to decide against the session it holds.
813
+ */
814
+ export const validateRegisterGatewaySessionRequest = (
815
+ valueArg: unknown,
816
+ pathArg = 'gateway session registration',
817
+ ): string[] => {
818
+ const record = readExactDataRecord(valueArg, registerSessionKeys);
819
+ if (record === null) {
820
+ return [`${pathArg} must use its exact schema`];
821
+ }
822
+ const errors = [
823
+ ...validateControllerNonNegativeInteger(record.registrationSequence, `${pathArg} registrationSequence`),
824
+ ...validateVersion(record.dcrouterVersion, `${pathArg} dcrouterVersion`),
825
+ ...validateVersion(record.interfacesVersion, `${pathArg} interfacesVersion`),
826
+ ...validateControllerAreas(record.controllerAreas, `${pathArg} controllerAreas`),
827
+ ...validateGatewayApplyReport(record.applied, `${pathArg} applied`),
828
+ ];
829
+ if (record.known !== null) {
830
+ const known = readExactDataRecord(record.known, ['controllerId', 'epoch']);
831
+ errors.push(...(known === null
832
+ ? [`${pathArg} known must be null or use its exact schema`]
833
+ : [
834
+ ...validateControllerIdentifier(known.controllerId, `${pathArg} known controllerId`),
835
+ ...validateControllerCounter(known.epoch, `${pathArg} known epoch`),
836
+ ]));
837
+ }
838
+ return errors;
839
+ };
840
+
841
+ /**
842
+ * Validates one exported area table and names every reason it is refused. Whether the digest is
843
+ * `computeGatewayAreaTableDigest` of the content is the controller's to check.
844
+ */
845
+ export const validateGatewayAreaExport = (
846
+ valueArg: unknown,
847
+ pathArg = 'gateway area export',
848
+ ): string[] => {
849
+ const record = readExactDataRecord(valueArg, areaExportKeys);
850
+ if (record === null) {
851
+ return [`${pathArg} must use its exact schema`];
852
+ }
853
+ return [
854
+ ...validateArea(record.area, `${pathArg} area`),
855
+ ...validateDigest(record.digest, `${pathArg} digest`),
856
+ ...validateControllerStrictJson(record.content, `${pathArg} content`),
857
+ ];
858
+ };
859
+
860
+ const validateGatewayClientId = (valueArg: unknown, pathArg: string): string[] => (
861
+ isGatewayClientIdText(valueArg)
862
+ ? []
863
+ : [`${pathArg} must be 1 to ${externalGatewayBootstrapContract.maximumGatewayClientIdLength} visible ASCII `
864
+ + 'characters']
865
+ );
866
+
867
+ /** The host of a legacy gateway URL: an IPv6 literal, or lowercase RFC 1123 labels (IPv4 included). */
868
+ const isLegacyGatewayUrlHost = (hostnameArg: string): boolean => (
869
+ /^\[[0-9a-f:.]+\]$/.test(hostnameArg)
870
+ || (hostnameArg.length <= gatewayConnectorContract.maximumHostnameLength
871
+ && hostnameArg.split('.').every((labelArg) => dnsZoneLabel.test(labelArg)))
872
+ );
873
+
874
+ const validateLegacyGatewayUrl = (valueArg: unknown, pathArg: string): string[] => {
875
+ const maximum = externalGatewayBootstrapContract.maximumGatewayUrlLength;
876
+ const refusal = [`${pathArg} must be an absolute http or https URL of at most ${maximum} characters in its `
877
+ + 'canonical spelling, without userinfo, query, fragment or trailing slash'];
878
+ if (typeof valueArg !== 'string' || valueArg.length === 0 || valueArg.length > maximum) {
879
+ return refusal;
880
+ }
881
+ let parsed: URL;
882
+ try {
883
+ parsed = new URL(valueArg);
884
+ } catch {
885
+ return refusal;
886
+ }
887
+ return (parsed.protocol === 'http:' || parsed.protocol === 'https:')
888
+ && parsed.username === '' && parsed.password === '' && parsed.search === '' && parsed.hash === ''
889
+ && isLegacyGatewayUrlHost(parsed.hostname)
890
+ && !valueArg.endsWith('/')
891
+ && parsed.href.replace(/\/+$/, '') === valueArg
892
+ ? []
893
+ : refusal;
894
+ };
895
+
896
+ /** 0 to the allowlist's maximum prefixes; a non-empty list follows `validateClusterRouteSourceAllowList`. */
897
+ const validateForwardSourcePrefixes = (valueArg: unknown, pathArg: string): string[] => {
898
+ const maximum = clusterIngressLimits.maximumSourceAllowListEntries;
899
+ const prefixes = readDataElements(valueArg, maximum);
900
+ if (prefixes === null) {
901
+ return [`${pathArg} must list 0 to ${maximum} address prefixes`];
902
+ }
903
+ return prefixes.length === 0 ? [] : validateClusterRouteSourceAllowList(valueArg, pathArg);
904
+ };
905
+
906
+ const validateGatewayConnection = (valueArg: unknown, pathArg: string): string[] => {
907
+ const kind = readDataProperty(valueArg, 'kind')?.value;
908
+ if (kind === 'legacy') {
909
+ const record = readExactDataRecord(valueArg, legacyConnectionKeys);
910
+ return record === null
911
+ ? [`${pathArg} must use the exact legacy schema`]
912
+ : [
913
+ ...validateLegacyGatewayUrl(record.url, `${pathArg} url`),
914
+ ...validateGatewayClientId(record.gatewayClientId, `${pathArg} gatewayClientId`),
915
+ ];
916
+ }
917
+ if (kind === 'adopted') {
918
+ const record = readExactDataRecord(valueArg, adoptedConnectionKeys);
919
+ return record === null
920
+ ? [`${pathArg} must use the exact adopted schema`]
921
+ : [
922
+ ...validateControllerNonNegativeInteger(record.adoptedAt, `${pathArg} adoptedAt`),
923
+ ...validateControllerIdentifier(record.machineUserId, `${pathArg} machineUserId`),
924
+ ...validateControllerCounter(record.credentialGeneration, `${pathArg} credentialGeneration`),
925
+ ...validateNullable(record.controllerGatewayClientId, `${pathArg} controllerGatewayClientId`,
926
+ validateGatewayClientId),
927
+ ];
928
+ }
929
+ return [`${pathArg} kind must be one of legacy, adopted`];
930
+ };
931
+
932
+ /**
933
+ * Validates one gateway record and names every reason it is refused.
934
+ *
935
+ * The record alone: whether its name is unique, its location exists and at most one gateway is the
936
+ * controller gateway is the controller's to judge against the gateways it records.
937
+ */
938
+ export const validateGateway = (
939
+ valueArg: unknown,
940
+ pathArg = 'gateway',
941
+ ): string[] => {
942
+ const record = readExactDataRecord(valueArg, gatewayKeys);
943
+ if (record === null) {
944
+ return [`${pathArg} must use its exact schema`];
945
+ }
946
+ return [
947
+ ...validateControllerIdentifier(record.id, `${pathArg} id`),
948
+ ...(isGatewayName(record.name)
949
+ ? []
950
+ : [`${pathArg} name must be one lowercase RFC 1123 label of 1 to 63 characters`]),
951
+ ...validateControllerIdentifier(record.locationId, `${pathArg} locationId`),
952
+ ...validateForwardSourcePrefixes(record.forwardSourcePrefixes, `${pathArg} forwardSourcePrefixes`),
953
+ ...validateGatewayConnection(record.connection, `${pathArg} connection`),
954
+ ];
955
+ };