@serve.zone/interfaces 32.124.0 → 32.126.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 (42) hide show
  1. package/changelog.md +16 -0
  2. package/dist_ts/00_commitinfo_data.js +1 -1
  3. package/dist_ts/data/certificateauthority.d.ts +57 -0
  4. package/dist_ts/data/certificateauthority.js +69 -0
  5. package/dist_ts/data/externaldns.d.ts +135 -0
  6. package/dist_ts/data/externaldns.js +138 -0
  7. package/dist_ts/data/gateway.d.ts +17 -0
  8. package/dist_ts/data/gateway.js +1 -1
  9. package/dist_ts/data/hetzner.d.ts +6 -0
  10. package/dist_ts/data/hetzner.js +17 -1
  11. package/dist_ts/data/index.d.ts +4 -0
  12. package/dist_ts/data/index.js +5 -1
  13. package/dist_ts/data/nattraversal.d.ts +98 -0
  14. package/dist_ts/data/nattraversal.js +172 -0
  15. package/dist_ts/data/pathrouting.d.ts +170 -0
  16. package/dist_ts/data/pathrouting.js +227 -0
  17. package/dist_ts/requests/certificateauthority.d.ts +118 -0
  18. package/dist_ts/requests/certificateauthority.js +2 -0
  19. package/dist_ts/requests/externaldns.d.ts +213 -0
  20. package/dist_ts/requests/externaldns.js +2 -0
  21. package/dist_ts/requests/hetzner.d.ts +7 -0
  22. package/dist_ts/requests/index.d.ts +5 -1
  23. package/dist_ts/requests/index.js +6 -2
  24. package/dist_ts/requests/nattraversal.d.ts +47 -0
  25. package/dist_ts/requests/nattraversal.js +2 -0
  26. package/dist_ts/requests/pathrouting.d.ts +107 -0
  27. package/dist_ts/requests/pathrouting.js +2 -0
  28. package/package.json +33 -1
  29. package/ts/00_commitinfo_data.ts +1 -1
  30. package/ts/data/certificateauthority.ts +115 -0
  31. package/ts/data/externaldns.ts +273 -0
  32. package/ts/data/gateway.ts +17 -0
  33. package/ts/data/hetzner.ts +22 -0
  34. package/ts/data/index.ts +4 -0
  35. package/ts/data/nattraversal.ts +261 -0
  36. package/ts/data/pathrouting.ts +410 -0
  37. package/ts/requests/certificateauthority.ts +139 -0
  38. package/ts/requests/externaldns.ts +263 -0
  39. package/ts/requests/hetzner.ts +7 -0
  40. package/ts/requests/index.ts +8 -0
  41. package/ts/requests/nattraversal.ts +63 -0
  42. package/ts/requests/pathrouting.ts +134 -0
@@ -0,0 +1,273 @@
1
+ export const externalDnsProviderTypes = Object.freeze([
2
+ 'cloudflare',
3
+ ] as const);
4
+
5
+ export type TExternalDnsProviderType = typeof externalDnsProviderTypes[number];
6
+
7
+ export const externalDnsRecordTypes = Object.freeze([
8
+ 'A',
9
+ 'AAAA',
10
+ 'CNAME',
11
+ 'TXT',
12
+ 'MX',
13
+ 'SRV',
14
+ 'CAA',
15
+ 'NS',
16
+ ] as const);
17
+
18
+ export type TExternalDnsRecordType = typeof externalDnsRecordTypes[number];
19
+
20
+ export const externalDnsRefusalCodes = Object.freeze([
21
+ 'administrator-required',
22
+ 'fresh-sign-in-required',
23
+ 'invalid-request',
24
+ 'provider-not-found',
25
+ 'provider-name-conflict',
26
+ 'provider-in-use',
27
+ 'zone-not-found',
28
+ 'record-not-found',
29
+ 'record-conflict',
30
+ 'precondition-failed',
31
+ 'provider-unavailable',
32
+ 'protected-hostname',
33
+ 'invalid-record-value',
34
+ 'mutation-not-found',
35
+ ] as const);
36
+
37
+ export type TExternalDnsRefusalCode = typeof externalDnsRefusalCodes[number];
38
+
39
+ export const externalDnsMutationActions = Object.freeze([
40
+ 'create',
41
+ 'update',
42
+ 'delete',
43
+ 'takeover',
44
+ 'rollback',
45
+ ] as const);
46
+
47
+ export type TExternalDnsMutationAction = typeof externalDnsMutationActions[number];
48
+
49
+ export const externalDnsContract = Object.freeze({
50
+ managementMarkerPrefix: 'servezone:cloudly:',
51
+ defaultTtlSeconds: 60,
52
+ minimumTtlSeconds: 1,
53
+ maximumTtlSeconds: 86_400,
54
+ maximumProviderNameLength: 160,
55
+ maximumHostnameLength: 253,
56
+ maximumRecordValueLength: 4_096,
57
+ maximumBatchRecords: 200,
58
+ } as const);
59
+
60
+ export interface IExternalDnsProviderTokenMetadata {
61
+ configured: boolean;
62
+ updatedAt: number | null;
63
+ /** Short SHA-256 prefix fingerprint (never the token itself). */
64
+ fingerprint: string | null;
65
+ }
66
+
67
+ export interface IExternalDnsProvider {
68
+ id: string;
69
+ name: string;
70
+ type: TExternalDnsProviderType;
71
+ enabled: boolean;
72
+ token: IExternalDnsProviderTokenMetadata;
73
+ status: 'untested' | 'ok' | 'error';
74
+ lastTestedAt: number | null;
75
+ lastSyncedAt: number | null;
76
+ lastError: string | null;
77
+ zoneCount: number;
78
+ createdAt: number;
79
+ updatedAt: number;
80
+ }
81
+
82
+ export interface IExternalDnsZone {
83
+ id: string;
84
+ providerId: string;
85
+ name: string;
86
+ externalZoneId: string;
87
+ nameservers: string[];
88
+ recordCount: number;
89
+ lastSyncedAt: number;
90
+ createdAt: number;
91
+ updatedAt: number;
92
+ }
93
+
94
+ export interface IExternalDnsRecord {
95
+ id: string;
96
+ providerId: string;
97
+ zoneName: string;
98
+ providerRecordId: string;
99
+ name: string;
100
+ type: TExternalDnsRecordType;
101
+ value: string;
102
+ ttl: number;
103
+ proxied: boolean;
104
+ ownership: 'cloudly' | 'unmanaged';
105
+ managementMarker: string | null;
106
+ ownerKey: string | null;
107
+ updatedAt: number;
108
+ }
109
+
110
+ export interface IExternalDnsDesiredRecord {
111
+ name: string;
112
+ type: TExternalDnsRecordType;
113
+ value: string;
114
+ ttl?: number;
115
+ proxied?: boolean;
116
+ /** Stable Cloudly ownership key (e.g. `service:<id>` or `control-plane:cloudly`). */
117
+ ownerKey: string;
118
+ }
119
+
120
+ export interface IExternalDnsConflict {
121
+ fqdn: string;
122
+ zoneName: string;
123
+ providerId: string;
124
+ blockingRecords: IExternalDnsRecord[];
125
+ desiredRecords: IExternalDnsDesiredRecord[];
126
+ detectedAt: number;
127
+ message: string;
128
+ }
129
+
130
+ export interface IExternalDnsTakeoverPreview {
131
+ fqdn: string;
132
+ zoneName: string;
133
+ providerId: string;
134
+ blockingRecords: IExternalDnsRecord[];
135
+ desiredRecords: IExternalDnsDesiredRecord[];
136
+ willReplaceRecordIds: string[];
137
+ }
138
+
139
+ export interface IExternalDnsRecordSnapshot {
140
+ providerRecordId: string;
141
+ name: string;
142
+ type: TExternalDnsRecordType;
143
+ value: string;
144
+ ttl: number;
145
+ proxied: boolean;
146
+ managementMarker: string | null;
147
+ }
148
+
149
+ export interface IExternalDnsMutationJournalEntry {
150
+ id: string;
151
+ providerId: string;
152
+ zoneName: string;
153
+ fqdn: string;
154
+ action: TExternalDnsMutationAction;
155
+ actorId: string;
156
+ reason: string | null;
157
+ previousRecords: IExternalDnsRecordSnapshot[];
158
+ resultingRecords: IExternalDnsRecordSnapshot[];
159
+ rolledBackByMutationId: string | null;
160
+ createdAt: number;
161
+ }
162
+
163
+ export interface IExternalDnsReconcileSummary {
164
+ providerId: string;
165
+ zoneName: string;
166
+ applied: number;
167
+ unchanged: number;
168
+ deleted: number;
169
+ conflicts: IExternalDnsConflict[];
170
+ }
171
+
172
+ const hostnameLabelPattern = /^[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9])?$/;
173
+
174
+ export const isExternalDnsProviderType = (valueArg: unknown): valueArg is TExternalDnsProviderType =>
175
+ typeof valueArg === 'string' && (externalDnsProviderTypes as readonly string[]).includes(valueArg);
176
+
177
+ export const isExternalDnsRecordType = (valueArg: unknown): valueArg is TExternalDnsRecordType =>
178
+ typeof valueArg === 'string' && (externalDnsRecordTypes as readonly string[]).includes(valueArg);
179
+
180
+ export const normalizeExternalDnsName = (nameArg: unknown): string | null => {
181
+ if (typeof nameArg !== 'string') return null;
182
+ const trimmed = nameArg.trim().toLowerCase().replace(/\.+$/, '');
183
+ if (trimmed.length === 0 || trimmed.length > externalDnsContract.maximumHostnameLength) return null;
184
+ const labels = trimmed.split('.');
185
+ if (labels.length < 2) return null;
186
+ const [first, ...rest] = labels;
187
+ const firstValid = first === '*' ? rest.length > 0 : hostnameLabelPattern.test(first);
188
+ if (!firstValid || !rest.every((labelArg) => hostnameLabelPattern.test(labelArg))) return null;
189
+ return trimmed;
190
+ };
191
+
192
+ export const normalizeExternalDnsZone = (zoneArg: unknown): string | null => {
193
+ const normalized = normalizeExternalDnsName(zoneArg);
194
+ if (!normalized || normalized.startsWith('*.')) return null;
195
+ return normalized;
196
+ };
197
+
198
+ export const isHostnameInZone = (fqdnArg: string, zoneNameArg: string): boolean => {
199
+ const fqdn = normalizeExternalDnsName(fqdnArg);
200
+ const zone = normalizeExternalDnsZone(zoneNameArg);
201
+ if (!fqdn || !zone) return false;
202
+ return fqdn === zone || fqdn.endsWith(`.${zone}`);
203
+ };
204
+
205
+ export const createCloudlyManagementMarker = (ownerKeyArg: string): string => {
206
+ const sanitized = ownerKeyArg.trim().replace(/\s+/g, '');
207
+ if (!sanitized || sanitized.length > 160) {
208
+ throw new Error('ownerKey must be a non-empty string of at most 160 characters');
209
+ }
210
+ return `${externalDnsContract.managementMarkerPrefix}${sanitized}`;
211
+ };
212
+
213
+ export const parseCloudlyManagementMarker = (markerArg: unknown): string | null => {
214
+ if (typeof markerArg !== 'string') return null;
215
+ const trimmed = markerArg.trim();
216
+ if (!trimmed.startsWith(externalDnsContract.managementMarkerPrefix)) return null;
217
+ const ownerKey = trimmed.slice(externalDnsContract.managementMarkerPrefix.length).trim();
218
+ return ownerKey.length > 0 ? ownerKey : null;
219
+ };
220
+
221
+ export const isCloudlyManagedMarker = (markerArg: unknown): boolean =>
222
+ parseCloudlyManagementMarker(markerArg) !== null;
223
+
224
+ /**
225
+ * Returns true when an existing record at the same FQDN conflicts with writing a desired record.
226
+ * CNAME records conflict with any other record type at the same name (RFC 1034 §3.6.2);
227
+ * otherwise records of the same type conflict unless owned by Cloudly.
228
+ */
229
+ export const isConflictingDnsRecordType = (
230
+ existingTypeArg: TExternalDnsRecordType,
231
+ desiredTypeArg: TExternalDnsRecordType,
232
+ ): boolean => {
233
+ if (existingTypeArg === desiredTypeArg) return true;
234
+ return existingTypeArg === 'CNAME' || desiredTypeArg === 'CNAME';
235
+ };
236
+
237
+ export const validateExternalDnsDesiredRecord = (recordArg: unknown): string[] => {
238
+ const errors: string[] = [];
239
+ if (recordArg === null || typeof recordArg !== 'object' || Array.isArray(recordArg)) {
240
+ return ['desired record must be an object'];
241
+ }
242
+ const candidate = recordArg as Record<string, unknown>;
243
+ if (normalizeExternalDnsName(candidate.name) === null) {
244
+ errors.push('name must be a valid DNS hostname');
245
+ }
246
+ if (!isExternalDnsRecordType(candidate.type)) {
247
+ errors.push('type must be a supported DNS record type');
248
+ }
249
+ if (
250
+ typeof candidate.value !== 'string'
251
+ || candidate.value.trim().length === 0
252
+ || candidate.value.length > externalDnsContract.maximumRecordValueLength
253
+ ) {
254
+ errors.push('value must be a non-empty string within maximum length');
255
+ }
256
+ if (candidate.ttl !== undefined) {
257
+ if (
258
+ typeof candidate.ttl !== 'number'
259
+ || !Number.isInteger(candidate.ttl)
260
+ || candidate.ttl < externalDnsContract.minimumTtlSeconds
261
+ || candidate.ttl > externalDnsContract.maximumTtlSeconds
262
+ ) {
263
+ errors.push('ttl must be an integer between 1 and 86400');
264
+ }
265
+ }
266
+ if (candidate.proxied !== undefined && typeof candidate.proxied !== 'boolean') {
267
+ errors.push('proxied must be a boolean when provided');
268
+ }
269
+ if (typeof candidate.ownerKey !== 'string' || candidate.ownerKey.trim().length === 0 || candidate.ownerKey.trim().length > 160) {
270
+ errors.push('ownerKey must be a non-empty string of at most 160 characters');
271
+ }
272
+ return errors;
273
+ };
@@ -287,6 +287,12 @@ export interface IGatewayCapabilities {
287
287
  configEvents?: true;
288
288
  /** The adopted controller session serves `readGatewayServiceHealth`. */
289
289
  serviceHealth?: true;
290
+ /** Multi-gateway optimal path routing capabilities advertised by the gateway. */
291
+ routing?: {
292
+ pathTelemetry?: true;
293
+ pathProbing?: true;
294
+ loopGuard?: true;
295
+ };
290
296
  routes: {
291
297
  read: boolean;
292
298
  write: boolean;
@@ -323,6 +329,11 @@ export interface IGatewayCapabilities {
323
329
  storeManagement?: true;
324
330
  /** Related wildcard import against an observed legacy backing on the adopted session. */
325
331
  storeRelatedImport?: true;
332
+ /**
333
+ * When `true`, Cloudly owns ACME issuance and pushes leaf certificate bundles to the gateway
334
+ * via `pushGatewayCertificateBundle`; the gateway disables local ACME issuance.
335
+ */
336
+ controllerPushed?: true;
326
337
  };
327
338
  email: {
328
339
  domains: boolean;
@@ -358,6 +369,12 @@ export interface IGatewayCapabilities {
358
369
  providerManaged: boolean;
359
370
  /** The adopted connector serves redacted DNS diagnostics and stored-credential connection tests. */
360
371
  operations?: true;
372
+ /**
373
+ * When `true`, Cloudly owns external DNS providers (e.g. Cloudflare) directly: Cloudly strips
374
+ * external provider rows and API tokens from the gateway's pushed `dns` area, and the gateway
375
+ * skips external provider mirroring and external route DNS reconciliation.
376
+ */
377
+ externalProvidersDisabled?: true;
361
378
  /** The adopted connector pages records from its durable provider-zone mirror; no provider call is made. */
362
379
  providerRecords?: true;
363
380
  /**
@@ -126,6 +126,12 @@ export interface IManagedHetznerRemoteIngressRoleConfig {
126
126
  manualTcpPorts: number[];
127
127
  manualUdpPorts: number[];
128
128
  hubAllowedCidrs: string[];
129
+ /** Enable co-hosted RFC 5389 STUN responder + authenticated encrypted NAT relay on this edge. */
130
+ natRelayEnabled?: boolean;
131
+ /** UDP port for the co-hosted STUN responder (default 3478). */
132
+ stunPort?: number;
133
+ /** TCP/TLS port for the co-hosted encrypted packet relay (default 3479). */
134
+ relayPort?: number;
129
135
  }
130
136
 
131
137
  export interface IManagedHetznerBackupMxRoleConfig {
@@ -294,6 +300,10 @@ export function planManagedHetznerFirewallRules(
294
300
  tcpPorts.add(443);
295
301
  udpPorts.add(443);
296
302
  }
303
+ if (roleConfigArg.natRelayEnabled) {
304
+ udpPorts.add(roleConfigArg.stunPort ?? 3478);
305
+ tcpPorts.add(roleConfigArg.relayPort ?? 3479);
306
+ }
297
307
  for (const port of [...tcpPorts].sort((a, b) => a - b)) {
298
308
  rules.push({
299
309
  description: `RemoteIngress TCP ${port}`,
@@ -414,6 +424,18 @@ export function validateManagedHetznerHostDesired(desiredArg: IManagedHetznerHos
414
424
  errors.push(`invalid hubAllowedCidr: ${cidr}`);
415
425
  }
416
426
  }
427
+ if (desiredArg.roleConfig.stunPort !== undefined) {
428
+ const p = desiredArg.roleConfig.stunPort;
429
+ if (!Number.isInteger(p) || p < 1 || p > 65535) {
430
+ errors.push(`invalid remoteingress stunPort: ${String(p)}`);
431
+ }
432
+ }
433
+ if (desiredArg.roleConfig.relayPort !== undefined) {
434
+ const p = desiredArg.roleConfig.relayPort;
435
+ if (!Number.isInteger(p) || p < 1 || p > 65535) {
436
+ errors.push(`invalid remoteingress relayPort: ${String(p)}`);
437
+ }
438
+ }
417
439
  }
418
440
  return errors;
419
441
  }
package/ts/data/index.ts CHANGED
@@ -28,6 +28,7 @@ export * from './deploymentpreflight.js';
28
28
  export * from './deploymentreleaseredeploy.js';
29
29
  export * from './migration.js';
30
30
  export * from './dns.js';
31
+ export * from './externaldns.js';
31
32
  export * from './docker.js';
32
33
  export * from './domain.js';
33
34
  export * from './event.js';
@@ -94,8 +95,11 @@ export * from './baremetal.js';
94
95
  export * from './baseos.js';
95
96
  export * from './backup.js';
96
97
  export * from './backupmx.js';
98
+ export * from './certificateauthority.js';
99
+ export * from './pathrouting.js';
97
100
  export * from './backuprestorerefusal.js';
98
101
  export * from './hetzner.js';
102
+ export * from './nattraversal.js';
99
103
  export * from './clusternode.js';
100
104
  export * from './clusternodehostname.js';
101
105
  export * from './settings.js';
@@ -0,0 +1,261 @@
1
+ import { parseCanonicalIpAddress } from '../private/ipaddress.js';
2
+
3
+ export const natTraversalKinds = Object.freeze(['cone', 'symmetric', 'unknown'] as const);
4
+ export type TNatTraversalKind = typeof natTraversalKinds[number];
5
+
6
+ export const natEndpointCandidateKinds = Object.freeze(['lan', 'stun', 'static'] as const);
7
+ export type TNatEndpointCandidateKind = typeof natEndpointCandidateKinds[number];
8
+
9
+ export const natAnchorSources = Object.freeze(['hetzner-remoteingress', 'dcrouter-gateway'] as const);
10
+ export type TNatAnchorSource = typeof natAnchorSources[number];
11
+
12
+ export const natTraversalContract = Object.freeze({
13
+ defaultStunPort: 3478,
14
+ defaultRelayPort: 3479,
15
+ relayAlpn: 'servezone-relay/1',
16
+ tokenVersion: 1 as const,
17
+ defaultTokenTtlSecs: 3600,
18
+ maxTokenTtlSecs: 24 * 60 * 60,
19
+ maxAnchors: 32,
20
+ maxIssuerPublicKeys: 4,
21
+ maxCandidatesPerNode: 32,
22
+ endpointReportTtlMs: 5 * 60_000,
23
+ maximumIdLength: 128,
24
+ } as const);
25
+
26
+ export interface INatTraversalAnchor {
27
+ anchorId: string;
28
+ source: TNatAnchorSource;
29
+ region: string;
30
+ hostname: string;
31
+ ipv4: string | null;
32
+ ipv6: string | null;
33
+ stunPort: number;
34
+ relayPort: number;
35
+ /** `sha256:<43-char-base64url>` SPKI pin of the relay TLS identity, when reported. */
36
+ relayIdentityPin: string | null;
37
+ healthy: boolean;
38
+ updatedAt: number;
39
+ }
40
+
41
+ export interface INatTraversalAnchorMap {
42
+ revision: number;
43
+ generatedAt: number;
44
+ /** 1-2 active base64url-encoded 32-byte Ed25519 issuer public keys for offline relay verification. */
45
+ issuerPublicKeys: string[];
46
+ anchors: INatTraversalAnchor[];
47
+ }
48
+
49
+ export interface INatRelayAdmissionClaims {
50
+ v: 1;
51
+ nodeId: string;
52
+ /** Base64url-encoded 32-byte node public key (unpadded). */
53
+ nodePublicKey: string;
54
+ /** `'*'` or a specific `anchorId`. */
55
+ anchorScope: string;
56
+ iat: number;
57
+ exp: number;
58
+ }
59
+
60
+ export interface INodeNatEndpointCandidate {
61
+ kind: TNatEndpointCandidateKind;
62
+ ip: string;
63
+ port: number;
64
+ anchorId?: string | null;
65
+ observedAt: number;
66
+ }
67
+
68
+ export interface INodeNatEndpointReport {
69
+ nodeId: string;
70
+ /** Base64url-encoded 32-byte node public key (unpadded). */
71
+ publicKey: string;
72
+ natKind: TNatTraversalKind;
73
+ homeRelayAnchorId: string | null;
74
+ candidates: INodeNatEndpointCandidate[];
75
+ generation: number;
76
+ reportedAt: number;
77
+ }
78
+
79
+ export interface IPeerNatEndpointEntry {
80
+ nodeId: string;
81
+ publicKey: string;
82
+ natKind: TNatTraversalKind;
83
+ homeRelayAnchorId: string | null;
84
+ candidates: INodeNatEndpointCandidate[];
85
+ generation: number;
86
+ reportedAt: number;
87
+ }
88
+
89
+ export interface IPeerNatEndpointMap {
90
+ scope: string;
91
+ revision: number;
92
+ generatedAt: number;
93
+ anchorMap: INatTraversalAnchorMap;
94
+ /** Short-lived Ed25519-signed relay admission token for the requesting node. */
95
+ relayAdmissionToken: string;
96
+ relayAdmissionTokenExpiresAt: number;
97
+ peers: IPeerNatEndpointEntry[];
98
+ }
99
+
100
+ const base64Url32BytePattern = /^[A-Za-z0-9_-]{43}$/;
101
+ const spkiPinPattern = /^sha256:[A-Za-z0-9_-]{43}$/;
102
+ const safeIdPattern = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
103
+
104
+ export function isValidBase64Url32ByteKey(valueArg: unknown): valueArg is string {
105
+ return typeof valueArg === 'string' && base64Url32BytePattern.test(valueArg);
106
+ }
107
+
108
+ export function isValidRelayIdentityPin(valueArg: unknown): valueArg is string {
109
+ return typeof valueArg === 'string' && spkiPinPattern.test(valueArg);
110
+ }
111
+
112
+ export function isValidNatPort(valueArg: unknown): valueArg is number {
113
+ return typeof valueArg === 'number' && Number.isInteger(valueArg) && valueArg >= 1 && valueArg <= 65535;
114
+ }
115
+
116
+ export function validateNatTraversalAnchor(anchorArg: INatTraversalAnchor): string[] {
117
+ const errors: string[] = [];
118
+ if (!safeIdPattern.test(anchorArg.anchorId)) {
119
+ errors.push('anchorId must be a safe identifier (1-128 chars)');
120
+ }
121
+ if (!(natAnchorSources as readonly string[]).includes(anchorArg.source)) {
122
+ errors.push(`invalid anchor source: ${String(anchorArg.source)}`);
123
+ }
124
+ if (!anchorArg.region || anchorArg.region.length > 64) {
125
+ errors.push('region must be a non-empty string (<= 64 chars)');
126
+ }
127
+ if (!anchorArg.hostname || anchorArg.hostname.length > 253) {
128
+ errors.push('hostname must be a non-empty string (<= 253 chars)');
129
+ }
130
+ if (anchorArg.ipv4 === null && anchorArg.ipv6 === null) {
131
+ errors.push('anchor must have at least one of ipv4 or ipv6');
132
+ }
133
+ if (anchorArg.ipv4 !== null) {
134
+ const parsed = parseCanonicalIpAddress(anchorArg.ipv4);
135
+ if (!parsed || parsed.family !== 4) {
136
+ errors.push(`invalid anchor ipv4: ${anchorArg.ipv4}`);
137
+ }
138
+ }
139
+ if (anchorArg.ipv6 !== null) {
140
+ const parsed = parseCanonicalIpAddress(anchorArg.ipv6);
141
+ if (!parsed || parsed.family !== 6) {
142
+ errors.push(`invalid anchor ipv6: ${anchorArg.ipv6}`);
143
+ }
144
+ }
145
+ if (!isValidNatPort(anchorArg.stunPort)) {
146
+ errors.push(`invalid stunPort: ${String(anchorArg.stunPort)}`);
147
+ }
148
+ if (!isValidNatPort(anchorArg.relayPort)) {
149
+ errors.push(`invalid relayPort: ${String(anchorArg.relayPort)}`);
150
+ }
151
+ if (anchorArg.relayIdentityPin !== null && !isValidRelayIdentityPin(anchorArg.relayIdentityPin)) {
152
+ errors.push('relayIdentityPin must be sha256:<43-char base64url> or null');
153
+ }
154
+ if (!Number.isSafeInteger(anchorArg.updatedAt) || anchorArg.updatedAt < 0) {
155
+ errors.push('updatedAt must be a non-negative integer timestamp');
156
+ }
157
+ return errors;
158
+ }
159
+
160
+ export function validateNatTraversalAnchorMap(mapArg: INatTraversalAnchorMap): string[] {
161
+ const errors: string[] = [];
162
+ if (!Number.isSafeInteger(mapArg.revision) || mapArg.revision < 0) {
163
+ errors.push('revision must be a non-negative safe integer');
164
+ }
165
+ if (!Number.isSafeInteger(mapArg.generatedAt) || mapArg.generatedAt < 0) {
166
+ errors.push('generatedAt must be a non-negative safe integer');
167
+ }
168
+ if (
169
+ !Array.isArray(mapArg.issuerPublicKeys)
170
+ || mapArg.issuerPublicKeys.length === 0
171
+ || mapArg.issuerPublicKeys.length > natTraversalContract.maxIssuerPublicKeys
172
+ ) {
173
+ errors.push('issuerPublicKeys must contain 1-4 valid 32-byte base64url Ed25519 keys');
174
+ } else {
175
+ mapArg.issuerPublicKeys.forEach((key, idx) => {
176
+ if (!isValidBase64Url32ByteKey(key)) {
177
+ errors.push(`issuerPublicKeys[${idx}] must be a 43-char unpadded base64url 32-byte key`);
178
+ }
179
+ });
180
+ }
181
+ if (!Array.isArray(mapArg.anchors) || mapArg.anchors.length > natTraversalContract.maxAnchors) {
182
+ errors.push(`anchors must be an array of at most ${natTraversalContract.maxAnchors} entries`);
183
+ } else {
184
+ const seen = new Set<string>();
185
+ for (const anchor of mapArg.anchors) {
186
+ if (seen.has(anchor.anchorId)) {
187
+ errors.push(`duplicate anchorId: ${anchor.anchorId}`);
188
+ }
189
+ seen.add(anchor.anchorId);
190
+ errors.push(...validateNatTraversalAnchor(anchor));
191
+ }
192
+ }
193
+ return errors;
194
+ }
195
+
196
+ export function validateNodeNatEndpointReport(reportArg: INodeNatEndpointReport): string[] {
197
+ const errors: string[] = [];
198
+ if (!safeIdPattern.test(reportArg.nodeId)) {
199
+ errors.push('nodeId must be a safe identifier (1-128 chars)');
200
+ }
201
+ if (!isValidBase64Url32ByteKey(reportArg.publicKey)) {
202
+ errors.push('publicKey must be a 43-char unpadded base64url 32-byte key');
203
+ }
204
+ if (!(natTraversalKinds as readonly string[]).includes(reportArg.natKind)) {
205
+ errors.push(`invalid natKind: ${String(reportArg.natKind)}`);
206
+ }
207
+ if (reportArg.homeRelayAnchorId !== null && !safeIdPattern.test(reportArg.homeRelayAnchorId)) {
208
+ errors.push('homeRelayAnchorId must be a safe identifier or null');
209
+ }
210
+ if (!Number.isSafeInteger(reportArg.generation) || reportArg.generation < 1) {
211
+ errors.push('generation must be a positive safe integer');
212
+ }
213
+ if (!Number.isSafeInteger(reportArg.reportedAt) || reportArg.reportedAt < 0) {
214
+ errors.push('reportedAt must be a non-negative integer timestamp');
215
+ }
216
+ if (
217
+ !Array.isArray(reportArg.candidates)
218
+ || reportArg.candidates.length > natTraversalContract.maxCandidatesPerNode
219
+ ) {
220
+ errors.push(`candidates must contain at most ${natTraversalContract.maxCandidatesPerNode} entries`);
221
+ } else {
222
+ for (let i = 0; i < reportArg.candidates.length; i++) {
223
+ const c = reportArg.candidates[i];
224
+ if (!(natEndpointCandidateKinds as readonly string[]).includes(c.kind)) {
225
+ errors.push(`candidates[${i}].kind is invalid`);
226
+ }
227
+ if (!parseCanonicalIpAddress(c.ip)) {
228
+ errors.push(`candidates[${i}].ip is not a canonical IP address`);
229
+ }
230
+ if (!isValidNatPort(c.port)) {
231
+ errors.push(`candidates[${i}].port is invalid`);
232
+ }
233
+ if (c.anchorId !== undefined && c.anchorId !== null && !safeIdPattern.test(c.anchorId)) {
234
+ errors.push(`candidates[${i}].anchorId is invalid`);
235
+ }
236
+ if (!Number.isSafeInteger(c.observedAt) || c.observedAt < 0) {
237
+ errors.push(`candidates[${i}].observedAt is invalid`);
238
+ }
239
+ }
240
+ }
241
+ return errors;
242
+ }
243
+
244
+ /**
245
+ * Pure NAT classification from 2+ STUN reflexive candidates observed via distinct anchors
246
+ * on the same local UDP socket: identical `(ip, port)` across anchors indicates cone
247
+ * (endpoint-independent) NAT; differing mappings indicate symmetric (endpoint-dependent) NAT.
248
+ */
249
+ export function classifyNatFromStunCandidates(
250
+ candidatesArg: ReadonlyArray<Pick<INodeNatEndpointCandidate, 'kind' | 'ip' | 'port' | 'anchorId'>>,
251
+ ): TNatTraversalKind {
252
+ const stunByAnchor = new Map<string, { ip: string; port: number }>();
253
+ for (const c of candidatesArg) {
254
+ if (c.kind !== 'stun' || !c.anchorId) continue;
255
+ stunByAnchor.set(c.anchorId, { ip: c.ip, port: c.port });
256
+ }
257
+ if (stunByAnchor.size < 2) return 'unknown';
258
+ const values = [...stunByAnchor.values()];
259
+ const first = values[0];
260
+ return values.every((v) => v.ip === first.ip && v.port === first.port) ? 'cone' : 'symmetric';
261
+ }