@serve.zone/interfaces 32.76.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@serve.zone/interfaces",
3
- "version": "32.76.0",
3
+ "version": "32.77.0",
4
4
  "private": false,
5
5
  "description": "Shared TypeScript interfaces and TypedRequest contracts for the serve.zone ecosystem.",
6
6
  "exports": {
package/readme.md CHANGED
@@ -4338,9 +4338,54 @@ A gateway (dcrouter) dials its controller (Cloudly) on the controller's typedsoc
4338
4338
  never dialled once adopted. It authenticates with `registerCloudlyClientSession` as the machine
4339
4339
  identity it received at adoption, then says hello with `registerGatewaySession`; the gateway is the
4340
4340
  one that identity names and is never a request field. The controller records its gateways as
4341
- `data.IGateway`: every gateway stands in a location, and its `connection` is either `legacy` (the
4342
- dcrouter the controller still dials at a URL as a gateway client) or `adopted` (machine user and
4343
- credential generation, no URL).
4341
+ `data.IGateway` (`data.validateGateway`): every gateway stands in a location, carries a name unique
4342
+ among the controller's gateways (`data.isGatewayName`, the location name rule: one lowercase RFC 1123
4343
+ label of 1 to 63 characters) and its `forwardSourcePrefixes` as canonical address prefixes
4344
+ (`192.0.2.10/32`, the rules of `data.validateClusterRouteSourceAllowList`, empty when none). The
4345
+ adoption facts and status documents state plain addresses (`publicIps`, `proxyIps`,
4346
+ `forwardSourceAddresses`), never IPv4-mapped, and a controller writes such an address into the record
4347
+ as its host prefix (`/32`, `/128`). Its
4348
+ `connection` is either `legacy` (the dcrouter the controller still dials at a canonical http(s) URL
4349
+ as a gateway client) or `adopted` (machine user, credential generation and `controllerGatewayClientId`,
4350
+ no URL). A gateway's machine identity has the role `gateway` (`data.IIdentity`, `data.IUser`), so a
4351
+ guard that names roles excludes it by type.
4352
+
4353
+ - Controller gateway: the one gateway the controller's own gateway-client calls are bound to, a
4354
+ `legacy` gateway by its `gatewayClientId` and an `adopted` one by a non-null
4355
+ `controllerGatewayClientId`. A `new` adoption binds `null`; an `existing` re-adoption of a legacy
4356
+ gateway moves its `gatewayClientId` into `controllerGatewayClientId`; a re-adoption of an adopted
4357
+ gateway keeps the binding unchanged, `null` included; no operation changes a non-null binding to
4358
+ another value.
4359
+ - Socket calls, by how a call authenticates: the adopted controller gateway serves on the connector
4360
+ socket every call it serves under gateway-client control auth, which is the `requests.gateway`
4361
+ calls with `identity?`/`apiToken?`, and the `requests.mail` and `requests.webpush` calls with
4362
+ `IMailControlRequestAuth`/`IWebPushControlRequestAuth`; also `reprovisionCertificateDomain` and
4363
+ `getWebPushServiceStatus`, which the controller calls. Off the socket, on HTTP: the credential
4364
+ handover (`provisionGatewayClientCredential`, `finalizeGatewayClientCredential`) and every
4365
+ submission- or app-credential call workloads make (`enqueueMail`, `getMailDeliveryStatus`,
4366
+ `registerServiceMailEndpoint`, `enqueueWebPush`, `cancelWebPush`, `getWebPushDeliveryStatus`). The
4367
+ socket is authenticated as the gateway, so its calls carry no credential: `apiToken` is optional
4368
+ on `syncGatewayClientDnsRecord`, `getGatewayClientCertificate` and
4369
+ `releaseGatewayClientCertificate`, required over HTTP and omitted over the socket. A gateway adopted
4370
+ without a binding refuses them `gateway-client-unbound`.
4371
+ - Refusals: either side refuses a connector request, the controller a legacy gateway setting it no
4372
+ longer owns, and the gateway an HTTP call with a token of its controller-bound gateway client
4373
+ (`controller-gateway-adopted`), with one of `data.gatewayConnectorRefusals` (`data.isGatewayConnectorRefusal`), as
4374
+ a `TypedResponseError` whose `errorData` is `data.IGatewayConnectorRefusalErrorData`
4375
+ (`{ code, retryable: false }`) and whose text carries the detail: `adoption-code-unknown`,
4376
+ `adoption-code-expired`, `adoption-code-used`, `gateway-name-taken`, `gateway-not-found`,
4377
+ `controller-origin-invalid`, `credential-generation-stale`, `registration-sequence-not-advancing`,
4378
+ `controller-mismatch`, `controller-epoch-ahead`, `gateway-session-required`, `status-too-frequent`
4379
+ (send the newest status again after the interval), `controller-gateway-adopted`, `request-invalid`
4380
+ (the text carries the validator's sentences), `desired-state-stale` (the text names the applied
4381
+ epoch and revision), `gateway-mismatch`, `unsupported-area` (an export of an area the gateway does
4382
+ not take) and `gateway-client-unbound`. An unknown location stays `location-not-found`
4383
+ (`data.locationRefusals`).
4384
+ - Revisions: `data.IControllerRevision` is one record of the controller-wide sequence, validated
4385
+ exactly by `data.validateControllerRevision`: the actor's `sub` is `null` exactly for `system`,
4386
+ the bounds of `data.controllerRevisionContract` only ever rise,
4387
+ `changes` holds 1 to `data.controllerRevisionContract.maximumChanges` (1024) changes of strict
4388
+ canonical JSON, each object once, never `null` on both sides.
4344
4389
 
4345
4390
  - Adoption: an administrator makes a one-time code (`createGatewayAdoptionCode`, for a new gateway
4346
4391
  in an existing location or for an existing gateway record) and runs the answered `command` on
@@ -4353,11 +4398,14 @@ credential generation, no URL).
4353
4398
  - Desired state: the controller pushes the whole `data.IGatewayDesiredState` (`applyDesiredState`):
4354
4399
  `{ gatewayId, controllerId, epoch, revision, areas }`, one whole table per controller-owned area.
4355
4400
  Documents order by `(epoch, revision)` (`data.compareControllerRevisionOrder`): newer applies,
4356
- equal replays the stored report, older is refused `stale`. A gateway validates every table first,
4401
+ equal replays the stored report, older is refused `desired-state-stale`. A refusal of the whole
4402
+ document (`request-invalid`, `controller-mismatch`, `gateway-mismatch`, `desired-state-stale`) is
4403
+ answered on the request and never stored in a report. A gateway validates every table first,
4357
4404
  skips an area whose digest it already serves, applies the rest in
4358
4405
  `data.gatewayConfigAreaApplyOrder` (`security`, `dns`, `routes`, `mail`, `edges`) and stops at the
4359
4406
  first failure; `data.IGatewayApplyReport.appliedRevision` advances only when the whole document
4360
- applied. Refusals are `data.gatewayApplyRefusals`.
4407
+ applied. Per-area refusals are `data.gatewayApplyRefusals` (`invalid-table`, `unsupported-area`,
4408
+ `local-changed-since-export`, `apply-failed`).
4361
4409
  - Area content is untyped here (`content: unknown`); each area's content type and validator ship in
4362
4410
  the release that moves that area. Its digest is `data.computeGatewayAreaTableDigest(area, content)`,
4363
4411
  `sha256:<hex>` of the strict canonical JSON of the domain `serve.zone/gateway-area-table`, the area
@@ -4379,7 +4427,7 @@ credential generation, no URL).
4379
4427
  `data.gatewayConnectorContract.maximumListeningPortRanges` (1024) per transport; one port may
4380
4428
  appear in both lists. A gateway lowercases its zone names before reporting them in `dnsZones`.
4381
4429
  - Validators name every refusal and never run an accessor: `data.validateControllerPeerSet`,
4382
- `data.validateGatewayAdoptionFacts`, `data.validateRegisterGatewaySessionRequest`,
4430
+ `data.validateControllerRevision`, `data.validateGateway`, `data.validateGatewayAdoptionFacts`, `data.validateRegisterGatewaySessionRequest`,
4383
4431
  `data.validateGatewayDesiredState` (envelope only), `data.validateGatewayApplyReport`,
4384
4432
  `data.validateGatewayStatusDocument` and `data.validateGatewayAreaExport`.
4385
4433
 
@@ -3,6 +3,6 @@
3
3
  */
4
4
  export const commitinfo = {
5
5
  name: '@serve.zone/interfaces',
6
- version: '32.76.0',
6
+ version: '32.77.0',
7
7
  description: 'Shared TypeScript interfaces and TypedRequest contracts for the serve.zone ecosystem.'
8
8
  }
package/ts/data/backup.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { TBackupRestoreRefusal } from './backuprestorerefusal.js';
2
2
  import type { ICorestoreDatabaseAllocationReference } from './corestore.js';
3
+ import type { IIdentity } from './user.js';
3
4
 
4
5
  export type TBackupStatus =
5
6
  | 'pending'
@@ -221,7 +222,8 @@ export interface IArchivePruneResult {
221
222
  export interface IIsolatedRestoreActor {
222
223
  userId: string;
223
224
  type: 'human' | 'machine' | 'system';
224
- role?: 'admin' | 'user' | 'api' | 'cluster';
225
+ /** The acting identity's role, so the projection admits every role an identity can hold. */
226
+ role?: IIdentity['role'];
225
227
  }
226
228
 
227
229
  export type TIsolatedRestoreStatus =
@@ -1,9 +1,12 @@
1
1
  import {
2
2
  validateControllerCounter,
3
3
  validateControllerIdentifier,
4
+ validateControllerNonNegativeInteger,
4
5
  validateControllerOrigin,
6
+ validateControllerStrictJson,
5
7
  } from '../private/controllercontract.js';
6
- import { readDataElements, readExactDataRecord } from '../private/dataproperties.js';
8
+ import { readDataElements, readDataProperty, readExactDataRecord } from '../private/dataproperties.js';
9
+ import type { TCompleteKeyList } from '../private/keylist.js';
7
10
 
8
11
  /**
9
12
  * The controller as the components that dial it know it: which controller they belong to, which
@@ -41,9 +44,16 @@ export const compareControllerRevisionOrder = (
41
44
  rightArg: Readonly<{ epoch: number; revision: number }>,
42
45
  ): number => Math.sign(leftArg.epoch - rightArg.epoch) || Math.sign(leftArg.revision - rightArg.revision);
43
46
 
47
+ /** The bounds of `validateControllerRevision`; they may only rise, never fall. */
48
+ export const controllerRevisionContract = Object.freeze({
49
+ maximumDisplayNameLength: 256,
50
+ maximumChanges: 1024,
51
+ } as const);
52
+
44
53
  /**
45
54
  * One record of the controller-wide revision sequence, written in the same transaction as the
46
- * change it records. A secret appears in `changes` by its ids and versions only, never by value.
55
+ * change it records (`validateControllerRevision`). A secret appears in `changes` by its ids and
56
+ * versions only, never by value.
47
57
  */
48
58
  export interface IControllerRevision {
49
59
  /** A positive safe integer from the one controller-wide sequence. */
@@ -54,11 +64,19 @@ export interface IControllerRevision {
54
64
  at: number;
55
65
  actor: {
56
66
  kind: 'person' | 'machine' | 'system';
57
- /** The acting identity's subject; `null` for the controller itself (`system`). */
67
+ /**
68
+ * The acting identity's subject, the controller's user id of the person or machine; `null`
69
+ * exactly for the controller itself (`system`).
70
+ */
58
71
  sub: string | null;
72
+ /** 1 to `controllerRevisionContract.maximumDisplayNameLength` characters. */
59
73
  displayName: string;
60
74
  };
61
75
  kind: 'change' | 'adoption' | 'import' | 'revert';
76
+ /**
77
+ * 1 to `controllerRevisionContract.maximumChanges` changes, each object (`objectKind`,
78
+ * `objectId`) at most once.
79
+ */
62
80
  changes: {
63
81
  objectKind: string;
64
82
  objectId: string;
@@ -104,3 +122,97 @@ export const validateControllerPeerSet = (
104
122
  }
105
123
  return errors;
106
124
  };
125
+
126
+ const revisionKeyList = ['revision', 'epoch', 'at', 'actor', 'kind', 'changes'] as const;
127
+ const revisionKeys: TCompleteKeyList<IControllerRevision, typeof revisionKeyList> = revisionKeyList;
128
+ const actorKeyList = ['kind', 'sub', 'displayName'] as const;
129
+ const actorKeys: TCompleteKeyList<IControllerRevision['actor'], typeof actorKeyList> = actorKeyList;
130
+ const changeKeyList = ['objectKind', 'objectId', 'before', 'after'] as const;
131
+ const changeKeys: TCompleteKeyList<IControllerRevision['changes'][number], typeof changeKeyList> = changeKeyList;
132
+ const actorKinds: readonly IControllerRevision['actor']['kind'][] = ['person', 'machine', 'system'];
133
+ const revisionKinds: readonly IControllerRevision['kind'][] = ['change', 'adoption', 'import', 'revert'];
134
+
135
+ const validateRevisionActor = (valueArg: unknown, pathArg: string): string[] => {
136
+ const actor = readExactDataRecord(valueArg, actorKeys);
137
+ if (actor === null) {
138
+ return [`${pathArg} must use its exact schema`];
139
+ }
140
+ const errors: string[] = [];
141
+ if (!actorKinds.some((kindArg) => kindArg === actor.kind)) {
142
+ errors.push(`${pathArg} kind must be one of ${actorKinds.join(', ')}`);
143
+ } else if (actor.kind === 'system') {
144
+ if (actor.sub !== null) {
145
+ errors.push(`${pathArg} sub must be null for the system actor`);
146
+ }
147
+ } else {
148
+ errors.push(...validateControllerIdentifier(actor.sub, `${pathArg} sub`));
149
+ }
150
+ const { maximumDisplayNameLength } = controllerRevisionContract;
151
+ if (typeof actor.displayName !== 'string' || actor.displayName.length === 0
152
+ || actor.displayName.length > maximumDisplayNameLength) {
153
+ errors.push(`${pathArg} displayName must be a string of 1 to ${maximumDisplayNameLength} characters`);
154
+ }
155
+ return errors;
156
+ };
157
+
158
+ const validateRevisionChange = (valueArg: unknown, pathArg: string): string[] => {
159
+ const change = readExactDataRecord(valueArg, changeKeys);
160
+ if (change === null) {
161
+ return [`${pathArg} must use its exact schema`];
162
+ }
163
+ const errors = [
164
+ ...validateControllerIdentifier(change.objectKind, `${pathArg} objectKind`),
165
+ ...validateControllerIdentifier(change.objectId, `${pathArg} objectId`),
166
+ ...validateControllerStrictJson(change.before, `${pathArg} before`),
167
+ ...validateControllerStrictJson(change.after, `${pathArg} after`),
168
+ ];
169
+ if (change.before === null && change.after === null) {
170
+ errors.push(`${pathArg} must state the object before or after the change`);
171
+ }
172
+ return errors;
173
+ };
174
+
175
+ /**
176
+ * Validates one controller revision and names every reason it is refused.
177
+ *
178
+ * The record alone: whether the revision is the next of the controller's sequence, its epoch the
179
+ * controller's current one, and its changes what the transaction wrote, is the controller's to
180
+ * judge against its own store.
181
+ */
182
+ export const validateControllerRevision = (
183
+ valueArg: unknown,
184
+ pathArg = 'controller revision',
185
+ ): string[] => {
186
+ const record = readExactDataRecord(valueArg, revisionKeys);
187
+ if (record === null) {
188
+ return [`${pathArg} must use its exact schema`];
189
+ }
190
+ const errors = [
191
+ ...validateControllerCounter(record.revision, `${pathArg} revision`),
192
+ ...validateControllerCounter(record.epoch, `${pathArg} epoch`),
193
+ ...validateControllerNonNegativeInteger(record.at, `${pathArg} at`),
194
+ ...validateRevisionActor(record.actor, `${pathArg} actor`),
195
+ ];
196
+ if (!revisionKinds.some((kindArg) => kindArg === record.kind)) {
197
+ errors.push(`${pathArg} kind must be one of ${revisionKinds.join(', ')}`);
198
+ }
199
+ const { maximumChanges } = controllerRevisionContract;
200
+ const changes = readDataElements(record.changes, maximumChanges);
201
+ if (changes === null || changes.length === 0) {
202
+ errors.push(`${pathArg} changes must be a dense list of 1 to ${maximumChanges} changes`);
203
+ return errors;
204
+ }
205
+ changes.forEach((changeArg, indexArg) => {
206
+ errors.push(...validateRevisionChange(changeArg, `${pathArg} changes[${indexArg}]`));
207
+ });
208
+ // A change whose object is not stated as two strings is refused by its own validator and left out.
209
+ const objects = changes.flatMap((changeArg) => {
210
+ const objectKind = readDataProperty(changeArg, 'objectKind')?.value;
211
+ const objectId = readDataProperty(changeArg, 'objectId')?.value;
212
+ return typeof objectKind === 'string' && typeof objectId === 'string' ? [`${objectKind}\u0000${objectId}`] : [];
213
+ });
214
+ if (new Set(objects).size !== objects.length) {
215
+ errors.push(`${pathArg} changes must name each object once`);
216
+ }
217
+ return errors;
218
+ };
@@ -6,15 +6,20 @@ import {
6
6
  validateControllerCounter,
7
7
  validateControllerIdentifier,
8
8
  validateControllerNonNegativeInteger,
9
+ validateControllerStrictJson,
9
10
  } from '../private/controllercontract.js';
10
11
  import { readDataElements, readDataProperty, readExactDataRecord } from '../private/dataproperties.js';
11
- import { parseCanonicalIpAddress } from '../private/ipaddress.js';
12
+ import { ipv4PrefixOfMapped, parseCanonicalIpAddress } from '../private/ipaddress.js';
12
13
  import type { TCompleteKeyList } from '../private/keylist.js';
13
14
  import { networkDigest } from '../private/networkcontract.js';
14
15
  import { isCanonicalTokenList } from '../private/tokenlist.js';
16
+ import { isGatewayClientIdText } from '../private/gatewayclientid.js';
17
+ import { clusterIngressLimits, validateClusterRouteSourceAllowList } from './clusteringress.js';
15
18
  import { type IControllerPeerSet, validateControllerPeerSet } from './controller.js';
16
19
  import type { TSha256Digest } from './immutableimage.js';
20
+ import { isLocationName } from './location.js';
17
21
  import { isReleaseVersion } from './releaseversion.js';
22
+ import { externalGatewayBootstrapContract } from './settings.js';
18
23
 
19
24
  /*
20
25
  * The gateway connector (AGL-1182): a gateway (dcrouter) dials its controller (Cloudly) on the
@@ -60,20 +65,49 @@ export const gatewayConnectorContract = Object.freeze({
60
65
  } as const);
61
66
 
62
67
  /**
63
- * One gateway as its controller records it.
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`).
64
75
  *
65
76
  * `connection` says how the two reach each other. A `legacy` gateway is the dcrouter the
66
77
  * controller still dials at its URL as the named gateway client. An `adopted` gateway dials the
67
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.
68
84
  */
69
85
  export interface IGateway {
70
86
  id: string;
87
+ /** Unique among the controller's gateways; `isGatewayName`. */
71
88
  name: string;
72
89
  /** The location the gateway stands in (`data.ILocation`); every gateway stands in one. */
73
90
  locationId: string;
74
- forwardSourceAddresses: 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[];
75
100
  connection:
76
- | { kind: 'legacy'; url: string; gatewayClientId: string }
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
+ }
77
111
  | {
78
112
  kind: 'adopted';
79
113
  /** Unix milliseconds on the controller's clock. */
@@ -82,6 +116,17 @@ export interface IGateway {
82
116
  machineUserId: string;
83
117
  /** Raised by every re-adoption; the previous generation is dead from then on. */
84
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;
85
130
  };
86
131
  }
87
132
 
@@ -129,7 +174,7 @@ export interface IGatewayAreaTable {
129
174
  *
130
175
  * Documents are ordered by `(epoch, revision)` (`data.compareControllerRevisionOrder`): a newer one
131
176
  * is applied, an equal one is an idempotent replay answered with the stored report, and an older
132
- * one is refused `stale`.
177
+ * one is refused `desired-state-stale` (`gatewayConnectorRefusals`).
133
178
  */
134
179
  export interface IGatewayDesiredState {
135
180
  gatewayId: string;
@@ -141,14 +186,105 @@ export interface IGatewayDesiredState {
141
186
  }
142
187
 
143
188
  /**
144
- * Every reason a gateway refuses an area of a desired state. Each is reported per area in
145
- * `IGatewayAreaApplyState.refusal`.
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`.
146
201
  */
147
- export const gatewayApplyRefusals = Object.freeze([
148
- /** The document is older than the one the gateway applied, by `(epoch, revision)`. */
149
- 'stale',
150
- /** The document comes from another controller than the one that adopted the gateway. */
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
+ */
151
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([
152
288
  /** A table failed validation; a gateway validates every table first and then applies none. */
153
289
  'invalid-table',
154
290
  /** The document carries an area the gateway does not take from a controller (`controllerAreas`). */
@@ -340,6 +476,18 @@ const registerSessionKeys: TCompleteKeyList<IRegisterGatewaySessionRequest, type
340
476
  registerSessionKeyList;
341
477
  const areaExportKeyList = ['area', 'digest', 'content'] as const;
342
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;
343
491
 
344
492
  const areaOwners: readonly IGatewayAreaApplyState['owner'][] = ['controller', 'gateway'];
345
493
  const areaApplyStates: readonly IGatewayAreaApplyState['state'][] = ['applied', 'rejected', 'not-attempted'];
@@ -386,11 +534,16 @@ const validateAddresses = (valueArg: unknown, pathArg: string): string[] => {
386
534
  if (addresses === null) {
387
535
  return [`${pathArg} must be a dense list of at most ${gatewayConnectorContract.maximumAddresses} addresses`];
388
536
  }
389
- const errors = addresses.flatMap((addressArg, indexArg) => (
390
- parseCanonicalIpAddress(addressArg) === null
391
- ? [`${pathArg}[${indexArg}] must be a canonical IPv4 or IPv6 address`]
392
- : []
393
- ));
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
+ });
394
547
  if (new Set(addresses).size !== addresses.length) {
395
548
  errors.push(`${pathArg} must name each address once`);
396
549
  }
@@ -424,15 +577,6 @@ const validateKeyedList = (
424
577
  return errors;
425
578
  };
426
579
 
427
- const validateStrictJson = (valueArg: unknown, pathArg: string): string[] => {
428
- try {
429
- canonicalizeStrictJson(valueArg, failAreaTable, pathArg);
430
- return [];
431
- } catch {
432
- return [`${pathArg} must be strict canonical JSON: safe integers only, no undefined, cycle or accessor`];
433
- }
434
- };
435
-
436
580
  const validateAreaTable = (valueArg: unknown, pathArg: string): string[] => {
437
581
  const record = readExactDataRecord(valueArg, areaTableKeys);
438
582
  if (record === null) {
@@ -441,7 +585,7 @@ const validateAreaTable = (valueArg: unknown, pathArg: string): string[] => {
441
585
  const errors = [
442
586
  ...validateArea(record.area, `${pathArg} area`),
443
587
  ...validateDigest(record.digest, `${pathArg} digest`),
444
- ...validateStrictJson(record.content, `${pathArg} content`),
588
+ ...validateControllerStrictJson(record.content, `${pathArg} content`),
445
589
  ];
446
590
  if (record.takeover !== null) {
447
591
  const takeover = readExactDataRecord(record.takeover, ['localDigest']);
@@ -458,7 +602,7 @@ const validateAreaTable = (valueArg: unknown, pathArg: string): string[] => {
458
602
  * The envelope only: every table's digest has the digest form and its content is strict canonical
459
603
  * JSON, but whether the digest is `computeGatewayAreaTableDigest` of the content, what the content
460
604
  * of an area must hold, and how the document orders against the one applied are the gateway's to
461
- * judge (`invalid-table`, `stale`).
605
+ * judge (`invalid-table`, `desired-state-stale`).
462
606
  */
463
607
  export const validateGatewayDesiredState = (
464
608
  valueArg: unknown,
@@ -709,6 +853,103 @@ export const validateGatewayAreaExport = (
709
853
  return [
710
854
  ...validateArea(record.area, `${pathArg} area`),
711
855
  ...validateDigest(record.digest, `${pathArg} digest`),
712
- ...validateStrictJson(record.content, `${pathArg} content`),
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`),
713
954
  ];
714
955
  };