@serve.zone/interfaces 32.123.0 → 32.124.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.
@@ -0,0 +1,252 @@
1
+ import { compareWireTokens } from '../private/canonicaljson.js';
2
+ import { parseCanonicalIpAddress } from '../private/ipaddress.js';
3
+ import { validateManagedHetznerFqdn } from './hetzner.js';
4
+
5
+ export const backupMxContract = Object.freeze({
6
+ typedSocketPath: '/backupmx-socket',
7
+ defaultMxPriority: 30,
8
+ minimumMxPriority: 21,
9
+ maximumMxPriority: 65535,
10
+ maximumDomains: 1024,
11
+ maximumRecipientsPerDomain: 10_000,
12
+ maximumMessageSizeBytes: 50 * 1024 * 1024,
13
+ defaultMaxAgeMs: 5 * 24 * 60 * 60 * 1000,
14
+ defaultDsnMaxAgeMs: 2 * 24 * 60 * 60 * 1000,
15
+ defaultInitialRetryMs: 60_000,
16
+ defaultMaxRetryMs: 4 * 60 * 60 * 1000,
17
+ defaultScanIntervalMs: 15_000,
18
+ defaultMaxConcurrentDeliveries: 4,
19
+ maximumQueuePageLimit: 200,
20
+ credentialRandomBytes: 32,
21
+ } as const);
22
+
23
+ export const backupMxRefusals = Object.freeze([
24
+ 'request-invalid',
25
+ 'credential-invalid',
26
+ 'controller-mismatch',
27
+ 'controller-epoch-older',
28
+ 'config-epoch-stale',
29
+ 'instance-not-found',
30
+ 'instance-disconnected',
31
+ 'instance-queue-not-empty',
32
+ 'queue-item-not-found',
33
+ 'queue-item-not-dead',
34
+ ] as const);
35
+
36
+ export type TBackupMxRefusalCode = typeof backupMxRefusals[number];
37
+
38
+ export type TBackupMxRecipientPolicy =
39
+ | {
40
+ mode: 'allow-list';
41
+ /** Lowercase canonical `local@domain` addresses sorted ascending (`compareWireTokens`). */
42
+ recipients: string[];
43
+ }
44
+ | {
45
+ /** Reflects a Cloudly/DcRouter managed domain whose inbound policy is catch-all store. */
46
+ mode: 'domain-catchall';
47
+ };
48
+
49
+ export interface IBackupMxManagedDomain {
50
+ /** Lowercase ASCII FQDN of a Cloudly/DcRouter-managed mail domain. */
51
+ domain: string;
52
+ /** Hostnames belonging to this Backup MX (loop guard — MX >= self are excluded). */
53
+ selfMxHostnames: string[];
54
+ /** Canonical IPv4/IPv6 addresses belonging to this Backup MX (additional loop guard). */
55
+ selfMxIps: string[];
56
+ recipientPolicy: TBackupMxRecipientPolicy;
57
+ }
58
+
59
+ export interface IBackupMxQueuePolicy {
60
+ maxAgeMs: number;
61
+ dsnMaxAgeMs: number;
62
+ initialRetryMs: number;
63
+ maxRetryMs: number;
64
+ jitter: number;
65
+ scanIntervalMs: number;
66
+ maxConcurrentDeliveries: number;
67
+ maxMessageSizeBytes: number;
68
+ }
69
+
70
+ export interface IBackupMxInboundTls {
71
+ certificatePem: string;
72
+ privateKeyPem: string;
73
+ fingerprintSha256: string;
74
+ expiresAt: number;
75
+ }
76
+
77
+ /**
78
+ * Canonical desired-state snapshot pushed by Cloudly to a Backup MX daemon over TypedSocket.
79
+ * Persisted locally on the Backup MX host so restarts during a Cloudly outage remain autonomous.
80
+ */
81
+ export interface IBackupMxDesiredState {
82
+ configEpoch: number;
83
+ hostname: string;
84
+ listenPorts: number[];
85
+ domains: IBackupMxManagedDomain[];
86
+ queuePolicy: IBackupMxQueuePolicy;
87
+ inboundTls: IBackupMxInboundTls | null;
88
+ }
89
+
90
+ export interface IBackupMxDomainStatus {
91
+ domain: string;
92
+ pendingCount: number;
93
+ deadCount: number;
94
+ circuitBlockedUntil: number | null;
95
+ lastDeliveredAt: number | null;
96
+ lastError: string | null;
97
+ }
98
+
99
+ export interface IBackupMxStatus {
100
+ instanceId: string;
101
+ hostname: string;
102
+ version: string;
103
+ bridgeState: string;
104
+ appliedConfigEpoch: number;
105
+ checkedAt: number;
106
+ queue: {
107
+ pending: number;
108
+ dead: number;
109
+ };
110
+ counters: {
111
+ acceptedTotal: number;
112
+ deliveredTotal: number;
113
+ retriedTotal: number;
114
+ permanentlyFailedTotal: number;
115
+ rejectedRecipientsTotal: number;
116
+ deliveryAttemptsTotal: number;
117
+ };
118
+ tlsCertificate: {
119
+ configured: boolean;
120
+ fingerprintSha256: string | null;
121
+ expiresAt: number | null;
122
+ };
123
+ domains: IBackupMxDomainStatus[];
124
+ }
125
+
126
+ export interface IBackupMxQueueItemSummary {
127
+ id: string;
128
+ queue: 'pending' | 'dead';
129
+ kind: 'relay' | 'dsn';
130
+ destinationDomain: string;
131
+ envelopeFrom: string;
132
+ recipients: string[];
133
+ sizeBytes: number;
134
+ createdAt: number;
135
+ attempts: number;
136
+ nextAttemptAt: number;
137
+ deadlineAt: number;
138
+ lastAttemptAt: number | null;
139
+ lastError: string | null;
140
+ deadAt: number | null;
141
+ }
142
+
143
+ export interface IBackupMxInstance {
144
+ id: string;
145
+ name: string;
146
+ hostname: string;
147
+ mxPriority: number;
148
+ ipv4: string | null;
149
+ ipv6: string | null;
150
+ hetznerHostId: string | null;
151
+ enabled: boolean;
152
+ connected: boolean;
153
+ desiredConfigEpoch: number;
154
+ appliedConfigEpoch: number;
155
+ /** Managed domain names currently assigned to this Backup MX. */
156
+ managedDomains: string[];
157
+ observedStatus: IBackupMxStatus | null;
158
+ lastConnectedAt: number | null;
159
+ createdAt: number;
160
+ updatedAt: number;
161
+ }
162
+
163
+ export function validateBackupMxHostname(hostnameArg: string): boolean {
164
+ return validateManagedHetznerFqdn(hostnameArg);
165
+ }
166
+
167
+ export function validateBackupMxDesiredState(stateArg: IBackupMxDesiredState): string[] {
168
+ const errors: string[] = [];
169
+ if (!Number.isSafeInteger(stateArg.configEpoch) || stateArg.configEpoch < 1) {
170
+ errors.push('configEpoch must be a positive safe integer');
171
+ }
172
+ if (!validateBackupMxHostname(stateArg.hostname)) {
173
+ errors.push('hostname must be a lowercase FQDN');
174
+ }
175
+ if (!Array.isArray(stateArg.listenPorts) || stateArg.listenPorts.length === 0) {
176
+ errors.push('listenPorts must be a non-empty array of valid ports');
177
+ } else {
178
+ for (const port of stateArg.listenPorts) {
179
+ if (!Number.isSafeInteger(port) || port < 1 || port > 65535) {
180
+ errors.push(`invalid listenPort: ${port}`);
181
+ }
182
+ }
183
+ }
184
+ if (!Array.isArray(stateArg.domains) || stateArg.domains.length > backupMxContract.maximumDomains) {
185
+ errors.push(`domains must be an array of at most ${backupMxContract.maximumDomains} entries`);
186
+ } else {
187
+ let prevDomain: string | null = null;
188
+ for (const entry of stateArg.domains) {
189
+ if (!validateBackupMxHostname(entry.domain)) {
190
+ errors.push(`invalid domain: ${entry.domain}`);
191
+ }
192
+ if (prevDomain !== null && compareWireTokens(prevDomain, entry.domain) >= 0) {
193
+ errors.push(`domains must be strictly ascending: ${entry.domain}`);
194
+ }
195
+ prevDomain = entry.domain;
196
+
197
+ if (!Array.isArray(entry.selfMxHostnames) || !entry.selfMxHostnames.includes(stateArg.hostname)) {
198
+ errors.push(`domain ${entry.domain} selfMxHostnames must include ${stateArg.hostname}`);
199
+ }
200
+ for (const ip of entry.selfMxIps) {
201
+ if (!parseCanonicalIpAddress(ip)) {
202
+ errors.push(`domain ${entry.domain} has non-canonical selfMxIp: ${ip}`);
203
+ }
204
+ }
205
+ if (entry.recipientPolicy.mode === 'allow-list') {
206
+ if (entry.recipientPolicy.recipients.length > backupMxContract.maximumRecipientsPerDomain) {
207
+ errors.push(`domain ${entry.domain} exceeds recipient allow-list limit`);
208
+ }
209
+ let prevRcpt: string | null = null;
210
+ for (const rcpt of entry.recipientPolicy.recipients) {
211
+ const at = rcpt.lastIndexOf('@');
212
+ if (at <= 0 || rcpt.slice(at + 1) !== entry.domain || rcpt !== rcpt.toLowerCase()) {
213
+ errors.push(`domain ${entry.domain} invalid recipient in allow-list: ${rcpt}`);
214
+ }
215
+ if (prevRcpt !== null && compareWireTokens(prevRcpt, rcpt) >= 0) {
216
+ errors.push(`domain ${entry.domain} recipients must be strictly ascending`);
217
+ }
218
+ prevRcpt = rcpt;
219
+ }
220
+ } else if (entry.recipientPolicy.mode !== 'domain-catchall') {
221
+ errors.push(`domain ${entry.domain} has invalid recipientPolicy mode`);
222
+ }
223
+ }
224
+ }
225
+
226
+ const qp = stateArg.queuePolicy;
227
+ if (!qp || typeof qp !== 'object') {
228
+ errors.push('queuePolicy is required');
229
+ } else {
230
+ if (!Number.isSafeInteger(qp.maxAgeMs) || qp.maxAgeMs < 60_000) errors.push('invalid queuePolicy.maxAgeMs');
231
+ if (!Number.isSafeInteger(qp.dsnMaxAgeMs) || qp.dsnMaxAgeMs < 60_000) errors.push('invalid queuePolicy.dsnMaxAgeMs');
232
+ if (!Number.isSafeInteger(qp.initialRetryMs) || qp.initialRetryMs < 1_000) errors.push('invalid queuePolicy.initialRetryMs');
233
+ if (!Number.isSafeInteger(qp.maxRetryMs) || qp.maxRetryMs < qp.initialRetryMs) errors.push('invalid queuePolicy.maxRetryMs');
234
+ if (typeof qp.jitter !== 'number' || !Number.isFinite(qp.jitter) || qp.jitter < 0 || qp.jitter > 0.5) errors.push('invalid queuePolicy.jitter');
235
+ if (!Number.isSafeInteger(qp.scanIntervalMs) || qp.scanIntervalMs < 1_000) errors.push('invalid queuePolicy.scanIntervalMs');
236
+ if (!Number.isSafeInteger(qp.maxConcurrentDeliveries) || qp.maxConcurrentDeliveries < 1 || qp.maxConcurrentDeliveries > 64) {
237
+ errors.push('invalid queuePolicy.maxConcurrentDeliveries');
238
+ }
239
+ if (!Number.isSafeInteger(qp.maxMessageSizeBytes) || qp.maxMessageSizeBytes < 1024 || qp.maxMessageSizeBytes > backupMxContract.maximumMessageSizeBytes) {
240
+ errors.push('invalid queuePolicy.maxMessageSizeBytes');
241
+ }
242
+ }
243
+
244
+ if (stateArg.inboundTls !== null) {
245
+ if (!stateArg.inboundTls.certificatePem.includes('BEGIN CERTIFICATE')
246
+ || !stateArg.inboundTls.privateKeyPem.includes('BEGIN ')) {
247
+ errors.push('inboundTls must contain PEM certificate and private key');
248
+ }
249
+ }
250
+
251
+ return errors;
252
+ }
@@ -335,6 +335,11 @@ export interface IGatewayCapabilities {
335
335
  * means unsupported.
336
336
  */
337
337
  observations?: boolean;
338
+ /**
339
+ * The mail area accepts `backupMxTargets` and `domains[].backupMxEnabled`. Cloudly may send
340
+ * those members only when the gateway advertises this flag.
341
+ */
342
+ backupMxTargets?: true;
338
343
  };
339
344
  remoteIngress: {
340
345
  enabled: boolean;
@@ -36,6 +36,7 @@ import type {
36
36
  IGatewayBlockRuleRow,
37
37
  IGatewayCoreMailCredentialVerifier,
38
38
  IGatewayCoreMailPeerRow,
39
+ IGatewayMailBackupMxTargetRow,
39
40
  IGatewayDnsClientHostnameRow,
40
41
  IGatewayDnsDomainRow,
41
42
  IGatewayDnsProtectedHostnameRow,
@@ -205,6 +206,7 @@ export interface IGatewayAreaRowWrites {
205
206
  smtpAccounts: IGatewaySmtpAccountRowWrite;
206
207
  identities: IGatewayMailIdentityRowWrite;
207
208
  coreMailPeers: IGatewayCoreMailPeerRowWrite;
209
+ backupMxTargets?: IGatewayMailBackupMxTargetRow;
208
210
  };
209
211
  edges: {
210
212
  hub: IGatewayEdgeHubSettings;
@@ -897,6 +897,11 @@ export interface IGatewayMailDomainRow {
897
897
  rateLimits: IGatewayMailDomainRateLimits | null;
898
898
  /** A set of edge ids or tags; empty reaches every mail edge (the gateway reads absent as empty). */
899
899
  edgeFilter: string[];
900
+ /**
901
+ * Optional opt-in to publish managed Backup MX records (e.g. `MX 30 backupmx.*`) for this domain.
902
+ * Sent only when the gateway advertises `email.backupMxTargets`.
903
+ */
904
+ backupMxEnabled?: boolean;
900
905
  }
901
906
 
902
907
  /** One SMTP submission account. */
@@ -968,6 +973,16 @@ export interface IGatewayCoreMailPeerRow {
968
973
  credentials: IGatewayCoreMailCredentialVerifier[];
969
974
  }
970
975
 
976
+ /** One managed Backup MX target published as a lower-priority MX record behind RemoteIngress mail edges. */
977
+ export interface IGatewayMailBackupMxTargetRow {
978
+ id: string;
979
+ hostname: string;
980
+ priority: number;
981
+ ipv4: string | null;
982
+ ipv6: string | null;
983
+ enabled: boolean;
984
+ }
985
+
971
986
  /** The `mail` area. */
972
987
  export interface IGatewayMailArea {
973
988
  /**
@@ -982,6 +997,11 @@ export interface IGatewayMailArea {
982
997
  smtpAccounts: IGatewaySmtpAccountRow[];
983
998
  identities: IGatewayMailIdentityRow[];
984
999
  coreMailPeers: IGatewayCoreMailPeerRow[];
1000
+ /**
1001
+ * Optional Backup MX targets for managed mail DNS reconciliation. Sent only when the gateway
1002
+ * advertises `email.backupMxTargets`.
1003
+ */
1004
+ backupMxTargets?: IGatewayMailBackupMxTargetRow[];
985
1005
  }
986
1006
 
987
1007
  // ---------------------------------------------------------------------------------------------
@@ -1830,12 +1830,21 @@ const validateMail = (scopeArg: IScope, contentArg: Record<string, unknown>, dns
1830
1830
  }
1831
1831
  });
1832
1832
  rowList(scopeArg, 'domains', contentArg.domains, bounds.domains, (rowScopeArg, rowArg) => {
1833
- const row = exact(rowScopeArg, rowArg, [
1834
- 'id', 'domain', 'linkedDomainId', 'subdomain', 'dkim', 'rateLimits', 'edgeFilter',
1835
- ], null);
1833
+ const hasBackupMxEnabled = isPlainRecord(rowArg) && Object.hasOwn(rowArg, 'backupMxEnabled');
1834
+ const row = exact(
1835
+ rowScopeArg,
1836
+ rowArg,
1837
+ hasBackupMxEnabled
1838
+ ? ['id', 'domain', 'linkedDomainId', 'subdomain', 'dkim', 'rateLimits', 'edgeFilter', 'backupMxEnabled']
1839
+ : ['id', 'domain', 'linkedDomainId', 'subdomain', 'dkim', 'rateLimits', 'edgeFilter'],
1840
+ null,
1841
+ );
1836
1842
  if (row === null) {
1837
1843
  return;
1838
1844
  }
1845
+ if (hasBackupMxEnabled) {
1846
+ checkBoolean(rowScopeArg, row.backupMxEnabled, 'backupMxEnabled');
1847
+ }
1839
1848
  check(rowScopeArg, isZoneName(row.domain), 'domain');
1840
1849
  if (typeof row.linkedDomainId !== 'string') {
1841
1850
  refuse(rowScopeArg, 'linkedDomainId', 'invalid-value');
@@ -1945,6 +1954,29 @@ const validateMail = (scopeArg: IScope, contentArg: Record<string, unknown>, dns
1945
1954
  checkText(rowScopeArg, row.transferOrigin, 'transferOrigin', 2048);
1946
1955
  checkCoreMailVerifiers(rowScopeArg, row.credentials);
1947
1956
  });
1957
+ if (Object.hasOwn(contentArg, 'backupMxTargets')) {
1958
+ const seenBackupHostnames = new Set<string>();
1959
+ rowList(scopeArg, 'backupMxTargets', contentArg.backupMxTargets, 64, (rowScopeArg, rowArg) => {
1960
+ const row = exact(rowScopeArg, rowArg, [
1961
+ 'id', 'hostname', 'priority', 'ipv4', 'ipv6', 'enabled',
1962
+ ], null);
1963
+ if (row === null) {
1964
+ return;
1965
+ }
1966
+ check(rowScopeArg, isZoneName(row.hostname), 'hostname');
1967
+ if (typeof row.hostname === 'string' && isZoneName(row.hostname)) {
1968
+ if (seenBackupHostnames.has(row.hostname)) {
1969
+ refuse(rowScopeArg, 'hostname', 'duplicate-key');
1970
+ } else {
1971
+ seenBackupHostnames.add(row.hostname);
1972
+ }
1973
+ }
1974
+ check(rowScopeArg, typeof row.priority === 'number' && Number.isSafeInteger(row.priority) && row.priority >= 21 && row.priority <= 65535, 'priority');
1975
+ checkNullableAddress(rowScopeArg, row.ipv4, 'ipv4', 4);
1976
+ checkNullableAddress(rowScopeArg, row.ipv6, 'ipv6', 6);
1977
+ checkBoolean(rowScopeArg, row.enabled, 'enabled');
1978
+ });
1979
+ }
1948
1980
  };
1949
1981
 
1950
1982
  // ---------------------------------------------------------------------------------------------
@@ -2151,7 +2183,11 @@ const validateArea = (
2151
2183
  refuse(scope, null, 'not-strict-json');
2152
2184
  return;
2153
2185
  }
2154
- const content = exact(scope, contentArg, gatewayAreaMembers[areaArg], null);
2186
+ const hasBackupMxTargets = areaArg === 'mail' && isPlainRecord(contentArg) && Object.hasOwn(contentArg, 'backupMxTargets');
2187
+ const expectedKeys = hasBackupMxTargets
2188
+ ? [...gatewayAreaMembers.mail, 'backupMxTargets']
2189
+ : gatewayAreaMembers[areaArg];
2190
+ const content = exact(scope, contentArg, expectedKeys, null);
2155
2191
  if (content === null) {
2156
2192
  return;
2157
2193
  }