@serve.zone/interfaces 32.116.0 → 32.117.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.
@@ -1,8 +1,9 @@
1
1
  import { validateControllerIdentifier, validateControllerOrigin } from '../private/controllercontract.js';
2
- import { isPlainRecord, readDataProperty, readExactDataRecord } from '../private/dataproperties.js';
2
+ import { hasExactKeys, isPlainRecord, readDataProperties, readDataProperty, readExactDataRecord } from '../private/dataproperties.js';
3
3
  import { isClusterNodeId } from '../private/nodeidentifier.js';
4
4
  import { isBoundedInteger } from '../private/runtimepolicy.js';
5
5
  import { validateServiceId } from './coremail.runtime.js';
6
+ import { isSha256Digest, type TSha256Digest } from './immutableimage.js';
6
7
 
7
8
  export type TCorestoreReplicationRole = 'primary' | 'replica' | 'standalone';
8
9
 
@@ -59,6 +60,16 @@ export interface ICorestoreReplicationFence {
59
60
  timeline: ICorestoreReplicationTimeline;
60
61
  }
61
62
 
63
+ /** Rate limits, authenticated peer certificate pin and connection timers for the direct route. */
64
+ export interface ICorestoreReplicationTransportPolicy {
65
+ maxBytesPerSecond: number;
66
+ burstBytes: number;
67
+ peerCertificateSha256: TSha256Digest;
68
+ keepaliveIntervalMs: number;
69
+ reconnectBackoffMaxMs: number;
70
+ connectTimeoutMs: number;
71
+ }
72
+
62
73
  /**
63
74
  * Cloudly authorizes this directed binding and both Corestores persist the metadata. Replication
64
75
  * proceeds directly between authenticated peers during Cloudly downtime. Each peer compares the
@@ -69,6 +80,8 @@ export interface ICorestoreReplicationGrant {
69
80
  fence: ICorestoreReplicationFence;
70
81
  primary: ICorestoreReplicationPeer;
71
82
  replica: ICorestoreReplicationPeer;
83
+ /** Omit for peers whose exact grant reader predates the transport policy. */
84
+ transportPolicy?: ICorestoreReplicationTransportPolicy;
72
85
  }
73
86
 
74
87
  /** An authenticated, durable source receipt for a planned switchover. */
@@ -187,15 +200,36 @@ export const snapshotCorestoreReplicationFence = (value: unknown): ICorestoreRep
187
200
  };
188
201
  };
189
202
 
203
+ export const snapshotCorestoreReplicationTransportPolicy = (value: unknown): ICorestoreReplicationTransportPolicy => {
204
+ const policy = exact(value, [
205
+ 'maxBytesPerSecond', 'burstBytes', 'peerCertificateSha256',
206
+ 'keepaliveIntervalMs', 'reconnectBackoffMaxMs', 'connectTimeoutMs',
207
+ ]);
208
+ const { peerCertificateSha256 } = policy;
209
+ if (typeof peerCertificateSha256 !== 'string' || !isSha256Digest(peerCertificateSha256)) return invalid();
210
+ return {
211
+ maxBytesPerSecond: counter(policy.maxBytesPerSecond, 1),
212
+ burstBytes: counter(policy.burstBytes, 1),
213
+ peerCertificateSha256,
214
+ keepaliveIntervalMs: counter(policy.keepaliveIntervalMs, 1),
215
+ reconnectBackoffMaxMs: counter(policy.reconnectBackoffMaxMs, 1),
216
+ connectTimeoutMs: counter(policy.connectTimeoutMs, 1),
217
+ };
218
+ };
219
+
190
220
  /** Check the grant shape. Consumers resolve both peer/binding identities from trusted records. */
191
221
  export const snapshotCorestoreReplicationGrant = (value: unknown): ICorestoreReplicationGrant => {
192
- const grant = exact(value, ['fence', 'primary', 'replica']);
222
+ const grant = readDataProperties(value) ?? invalid();
223
+ if (!hasExactKeys(grant, ['fence', 'primary', 'replica'], ['transportPolicy'])) return invalid();
193
224
  const primary = peerOf(grant.primary);
194
225
  const replica = peerOf(grant.replica);
195
226
  if (primary.locationId === replica.locationId || primary.clusterId === replica.clusterId
196
227
  || primary.nodeId === replica.nodeId || primary.peerIdentityId === replica.peerIdentityId
197
228
  || primary.directOrigin === replica.directOrigin) return invalid();
198
- return { fence: snapshotCorestoreReplicationFence(grant.fence), primary, replica };
229
+ const snapshot = { fence: snapshotCorestoreReplicationFence(grant.fence), primary, replica };
230
+ return Object.hasOwn(grant, 'transportPolicy')
231
+ ? { ...snapshot, transportPolicy: snapshotCorestoreReplicationTransportPolicy(grant.transportPolicy) }
232
+ : snapshot;
199
233
  };
200
234
 
201
235
  export const snapshotCorestoreReplicationQuiescence = (value: unknown): ICorestoreReplicationQuiescence => {
@@ -0,0 +1,275 @@
1
+ import { isCanonicalBase64url32 } from '../private/bearerencoding.js';
2
+ import { validateControllerIdentifier } from '../private/controllercontract.js';
3
+ import { readExactDataRecord } from '../private/dataproperties.js';
4
+ import { isClusterNodeId } from '../private/nodeidentifier.js';
5
+ import { isBoundedInteger } from '../private/runtimepolicy.js';
6
+ import { isSha256Digest, type TSha256Digest } from './immutableimage.js';
7
+
8
+ export const diskEncryptionContract = Object.freeze({
9
+ defaultSilenceLimitMs: 3_600_000,
10
+ minimumSilenceLimitMs: 60_000,
11
+ maximumSilenceLimitMs: 86_400_000,
12
+ challengeTtlMs: 60_000,
13
+ digestDomain: 'serve.zone/disk-encryption-key-release',
14
+ });
15
+
16
+ const machineKinds = ['node', 'dcrouter', 'oneboxHost'] as const;
17
+ const keyAlgorithms = ['ecdsa-p256', 'ed25519'] as const;
18
+
19
+ export type TDiskEncryptionMachineKind = typeof machineKinds[number];
20
+ export type TDiskEncryptionKeyAlgorithm = typeof keyAlgorithms[number];
21
+
22
+ export const diskEncryptionRefusals = Object.freeze([
23
+ 'machine-not-enrolled', 'machine-revoked', 'location-locked', 'location-destroyed', 'challenge-invalid',
24
+ 'challenge-expired', 'signature-invalid', 'silence-limit-exceeded', 'approval-not-found', 'approval-expired',
25
+ 'location-not-found', 'fresh-passkey-required', 'conflict', 'request-invalid',
26
+ ] as const);
27
+
28
+ export type TDiskEncryptionRefusal = typeof diskEncryptionRefusals[number];
29
+
30
+ /** Public metadata only. Cloudly verifies TPM binding before recording an identity. */
31
+ export interface IDiskEncryptionNodeIdentity {
32
+ machineId: string;
33
+ machineKind: TDiskEncryptionMachineKind;
34
+ locationId: string;
35
+ keyAlgorithm: TDiskEncryptionKeyAlgorithm;
36
+ publicKeyPem: string;
37
+ publicKeySha256: TSha256Digest;
38
+ tpmBound: true;
39
+ tpmAttestationDigest: TSha256Digest | null;
40
+ enrolledAt: number;
41
+ enrolledBy: string;
42
+ lastSeenAt: number | null;
43
+ revokedAt: number | null;
44
+ revision: number;
45
+ }
46
+
47
+ export interface IDiskEncryptionKeyReleaseChallenge {
48
+ challengeId: string;
49
+ machineId: string;
50
+ /** Canonical unpadded base64url of a 32-byte nonce. */
51
+ nonceBase64Url: string;
52
+ controllerId: string;
53
+ controllerEpoch: number;
54
+ issuedAt: number;
55
+ expiresAt: number;
56
+ }
57
+
58
+ export interface IDiskEncryptionKeyReleaseProof {
59
+ challengeId: string;
60
+ machineId: string;
61
+ ephemeralPublicKeyPem: string;
62
+ signatureBase64Url: string;
63
+ }
64
+
65
+ /** Only the released variant carries a wrapped disk key. Keep it out of logs and status reads. */
66
+ export type TDiskEncryptionKeyReleaseOutcome =
67
+ | {
68
+ status: 'released';
69
+ wrappedKeyBase64: string;
70
+ wrappingAlgorithm: 'ecdh-p256-hkdf-sha256-aes-256-gcm';
71
+ controllerPublicKeyPem: string;
72
+ /** Canonical base64 of the 96-bit AES-GCM IV. */
73
+ ivBase64: string;
74
+ /** Canonical base64 of the 128-bit AES-GCM authentication tag. */
75
+ authTagBase64: string;
76
+ keyVersion: number;
77
+ issuedAt: number;
78
+ }
79
+ | {
80
+ status: 'approval-required';
81
+ approvalId: string;
82
+ reason: 'silence-limit-exceeded';
83
+ silenceMs: number;
84
+ silenceLimitMs: number;
85
+ expiresAt: number;
86
+ }
87
+ | { status: 'refused'; code: TDiskEncryptionRefusal };
88
+
89
+ /** An offline recovery key's metadata. The recovery key itself never crosses this wire. */
90
+ export interface IDiskEncryptionLocationRecoveryKey {
91
+ locationId: string;
92
+ recoveryKeyId: string;
93
+ keyFingerprintSha256: TSha256Digest;
94
+ createdAt: number;
95
+ createdBy: string;
96
+ destroyedAt: number | null;
97
+ revision: number;
98
+ }
99
+
100
+ export interface IDiskEncryptionUnlockApproval {
101
+ approvalId: string;
102
+ machineId: string;
103
+ locationId: string;
104
+ requestedAt: number;
105
+ silenceMs: number;
106
+ status: 'pending' | 'approved' | 'consumed' | 'expired' | 'denied';
107
+ approvedBy: string | null;
108
+ approvedAt: number | null;
109
+ expiresAt: number;
110
+ }
111
+
112
+ const invalid = (): never => { throw new Error('Disk encryption contract rejected.'); };
113
+
114
+ const exact = (value: unknown, keys: readonly string[]) => readExactDataRecord(value, keys) ?? invalid();
115
+ const isIdentifier = (value: unknown): value is string => validateControllerIdentifier(value, 'identifier').length === 0;
116
+ const identifier = (value: unknown): string => isIdentifier(value) ? value : invalid();
117
+ const machineIdOf = (value: unknown): string => isClusterNodeId(value) ? value : identifier(value);
118
+ const integer = (value: unknown, minimum: number): number =>
119
+ isBoundedInteger(value, minimum, Number.MAX_SAFE_INTEGER) ? value : invalid();
120
+ const timestamp = (value: unknown, minimum: number): number | null =>
121
+ value === null ? null : integer(value, minimum);
122
+ const digest = (value: unknown): TSha256Digest =>
123
+ typeof value === 'string' && isSha256Digest(value) ? value : invalid();
124
+ const choice = <T extends string>(value: unknown, choices: readonly T[]): T =>
125
+ choices.find((candidate) => candidate === value) ?? invalid();
126
+
127
+ const base64Alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
128
+ const base64UrlAlphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
129
+
130
+ const assertZeroPadBits = (lastSextet: string, remainder: number, alphabet: string): void => {
131
+ if (remainder === 1 || (remainder === 2 && alphabet.indexOf(lastSextet) % 16 !== 0)
132
+ || (remainder === 3 && alphabet.indexOf(lastSextet) % 4 !== 0)) invalid();
133
+ };
134
+
135
+ const base64Of = (value: unknown, expectedBytes?: number): string => {
136
+ if (typeof value !== 'string' || value.length === 0 || value.length > 1024 || value.length % 4 !== 0
137
+ || !/^[A-Za-z0-9+/]+={0,2}$/.test(value)) return invalid();
138
+ const padding = value.endsWith('==') ? 2 : value.endsWith('=') ? 1 : 0;
139
+ assertZeroPadBits(value[value.length - padding - 1], (4 - padding) % 4, base64Alphabet);
140
+ if (expectedBytes !== undefined && value.length / 4 * 3 - padding !== expectedBytes) return invalid();
141
+ return value;
142
+ };
143
+
144
+ const signatureOf = (value: unknown): string => {
145
+ if (typeof value !== 'string' || value.length === 0 || value.length > 128
146
+ || !/^[A-Za-z0-9_-]+$/.test(value)) return invalid();
147
+ assertZeroPadBits(value[value.length - 1], value.length % 4, base64UrlAlphabet);
148
+ return value;
149
+ };
150
+
151
+ /** Check the public-key envelope. Cryptographic key parsing and algorithm checks belong to the owner. */
152
+ const publicKeyOf = (value: unknown): string => {
153
+ if (typeof value !== 'string' || value.length > 1024) return invalid();
154
+ const pem = /^-----BEGIN PUBLIC KEY-----\r?\n([A-Za-z0-9+/=\r\n]+)\r?\n-----END PUBLIC KEY-----(?:\r?\n)?$/.exec(value);
155
+ if (!pem) return invalid();
156
+ base64Of(pem[1].replace(/\r?\n/g, ''));
157
+ return value;
158
+ };
159
+
160
+ export const snapshotDiskEncryptionRefusal = (value: unknown): TDiskEncryptionRefusal => choice(value, diskEncryptionRefusals);
161
+
162
+ export const snapshotDiskEncryptionSilenceLimitMs = (value: unknown): number =>
163
+ isBoundedInteger(value, diskEncryptionContract.minimumSilenceLimitMs, diskEncryptionContract.maximumSilenceLimitMs)
164
+ ? value : invalid();
165
+
166
+ export const snapshotDiskEncryptionNodeIdentity = (value: unknown): IDiskEncryptionNodeIdentity => {
167
+ const identity = exact(value, [
168
+ 'machineId', 'machineKind', 'locationId', 'keyAlgorithm', 'publicKeyPem', 'publicKeySha256', 'tpmBound',
169
+ 'tpmAttestationDigest', 'enrolledAt', 'enrolledBy', 'lastSeenAt', 'revokedAt', 'revision',
170
+ ]);
171
+ if (identity.tpmBound !== true) return invalid();
172
+ const machineKind = choice(identity.machineKind, machineKinds);
173
+ const machineId = machineKind === 'node'
174
+ ? (isClusterNodeId(identity.machineId) ? identity.machineId : invalid())
175
+ : identifier(identity.machineId);
176
+ const enrolledAt = integer(identity.enrolledAt, 1);
177
+ const lastSeenAt = timestamp(identity.lastSeenAt, enrolledAt);
178
+ const revokedAt = timestamp(identity.revokedAt, lastSeenAt ?? enrolledAt);
179
+ return {
180
+ machineId, machineKind, locationId: identifier(identity.locationId),
181
+ keyAlgorithm: choice(identity.keyAlgorithm, keyAlgorithms), publicKeyPem: publicKeyOf(identity.publicKeyPem),
182
+ publicKeySha256: digest(identity.publicKeySha256), tpmBound: true,
183
+ tpmAttestationDigest: identity.tpmAttestationDigest === null ? null : digest(identity.tpmAttestationDigest),
184
+ enrolledAt, enrolledBy: identifier(identity.enrolledBy), lastSeenAt, revokedAt, revision: integer(identity.revision, 1),
185
+ };
186
+ };
187
+
188
+ export const snapshotDiskEncryptionKeyReleaseChallenge = (value: unknown): IDiskEncryptionKeyReleaseChallenge => {
189
+ const challenge = exact(value, [
190
+ 'challengeId', 'machineId', 'nonceBase64Url', 'controllerId', 'controllerEpoch', 'issuedAt', 'expiresAt',
191
+ ]);
192
+ const { nonceBase64Url } = challenge;
193
+ if (typeof nonceBase64Url !== 'string' || nonceBase64Url.length !== 43 || !isCanonicalBase64url32(nonceBase64Url)) {
194
+ return invalid();
195
+ }
196
+ const issuedAt = integer(challenge.issuedAt, 1);
197
+ const expiresAt = integer(challenge.expiresAt, 1);
198
+ if (expiresAt <= issuedAt || expiresAt - issuedAt > diskEncryptionContract.challengeTtlMs) return invalid();
199
+ return {
200
+ challengeId: identifier(challenge.challengeId), machineId: machineIdOf(challenge.machineId), nonceBase64Url,
201
+ controllerId: identifier(challenge.controllerId), controllerEpoch: integer(challenge.controllerEpoch, 1),
202
+ issuedAt, expiresAt,
203
+ };
204
+ };
205
+
206
+ export const snapshotDiskEncryptionKeyReleaseProof = (value: unknown): IDiskEncryptionKeyReleaseProof => {
207
+ const proof = exact(value, ['challengeId', 'machineId', 'ephemeralPublicKeyPem', 'signatureBase64Url']);
208
+ return {
209
+ challengeId: identifier(proof.challengeId), machineId: machineIdOf(proof.machineId),
210
+ ephemeralPublicKeyPem: publicKeyOf(proof.ephemeralPublicKeyPem), signatureBase64Url: signatureOf(proof.signatureBase64Url),
211
+ };
212
+ };
213
+
214
+ /** Reads the wire shape. Key possession, signatures, expiry and authorization are verified by Cloudly. */
215
+ export const snapshotDiskEncryptionKeyReleaseOutcome = (value: unknown): TDiskEncryptionKeyReleaseOutcome => {
216
+ const released = readExactDataRecord(value, [
217
+ 'status', 'wrappedKeyBase64', 'wrappingAlgorithm', 'controllerPublicKeyPem', 'ivBase64', 'authTagBase64',
218
+ 'keyVersion', 'issuedAt',
219
+ ]);
220
+ if (released?.status === 'released' && released.wrappingAlgorithm === 'ecdh-p256-hkdf-sha256-aes-256-gcm') {
221
+ return {
222
+ status: 'released', wrappedKeyBase64: base64Of(released.wrappedKeyBase64), wrappingAlgorithm: released.wrappingAlgorithm,
223
+ controllerPublicKeyPem: publicKeyOf(released.controllerPublicKeyPem), ivBase64: base64Of(released.ivBase64, 12),
224
+ authTagBase64: base64Of(released.authTagBase64, 16), keyVersion: integer(released.keyVersion, 1),
225
+ issuedAt: integer(released.issuedAt, 1),
226
+ };
227
+ }
228
+ const approval = readExactDataRecord(value, ['status', 'approvalId', 'reason', 'silenceMs', 'silenceLimitMs', 'expiresAt']);
229
+ if (approval?.status === 'approval-required' && approval.reason === 'silence-limit-exceeded') {
230
+ const silenceLimitMs = snapshotDiskEncryptionSilenceLimitMs(approval.silenceLimitMs);
231
+ const silenceMs = integer(approval.silenceMs, 1);
232
+ if (silenceMs <= silenceLimitMs) return invalid();
233
+ return {
234
+ status: 'approval-required', approvalId: identifier(approval.approvalId), reason: approval.reason,
235
+ silenceMs, silenceLimitMs, expiresAt: integer(approval.expiresAt, 1),
236
+ };
237
+ }
238
+ const refused = exact(value, ['status', 'code']);
239
+ if (refused.status !== 'refused') return invalid();
240
+ return { status: 'refused', code: snapshotDiskEncryptionRefusal(refused.code) };
241
+ };
242
+
243
+ export const snapshotDiskEncryptionLocationRecoveryKey = (value: unknown): IDiskEncryptionLocationRecoveryKey => {
244
+ const key = exact(value, [
245
+ 'locationId', 'recoveryKeyId', 'keyFingerprintSha256', 'createdAt', 'createdBy', 'destroyedAt', 'revision',
246
+ ]);
247
+ const createdAt = integer(key.createdAt, 1);
248
+ return {
249
+ locationId: identifier(key.locationId), recoveryKeyId: identifier(key.recoveryKeyId),
250
+ keyFingerprintSha256: digest(key.keyFingerprintSha256), createdAt, createdBy: identifier(key.createdBy),
251
+ destroyedAt: timestamp(key.destroyedAt, createdAt), revision: integer(key.revision, 1),
252
+ };
253
+ };
254
+
255
+ const approvalStatuses = ['pending', 'approved', 'consumed', 'expired', 'denied'] as const;
256
+
257
+ export const snapshotDiskEncryptionUnlockApproval = (value: unknown): IDiskEncryptionUnlockApproval => {
258
+ const approval = exact(value, [
259
+ 'approvalId', 'machineId', 'locationId', 'requestedAt', 'silenceMs', 'status', 'approvedBy', 'approvedAt', 'expiresAt',
260
+ ]);
261
+ const requestedAt = integer(approval.requestedAt, 1);
262
+ const expiresAt = integer(approval.expiresAt, 1);
263
+ const status = choice(approval.status, approvalStatuses);
264
+ const approvedBy = approval.approvedBy === null ? null : identifier(approval.approvedBy);
265
+ const approvedAt = timestamp(approval.approvedAt, requestedAt);
266
+ if (expiresAt <= requestedAt || (approvedBy === null) !== (approvedAt === null)
267
+ || (approvedAt !== null && approvedAt >= expiresAt)
268
+ || ((status === 'approved' || status === 'consumed') && approvedBy === null)
269
+ || ((status === 'pending' || status === 'denied') && approvedBy !== null)) return invalid();
270
+ return {
271
+ approvalId: identifier(approval.approvalId), machineId: machineIdOf(approval.machineId),
272
+ locationId: identifier(approval.locationId), requestedAt, silenceMs: integer(approval.silenceMs, 0),
273
+ status, approvedBy, approvedAt, expiresAt,
274
+ };
275
+ };
package/ts/data/index.ts CHANGED
@@ -14,6 +14,7 @@ export * from './corestorecontroltoken.js';
14
14
  export * from './corestorelegacyadoption.js';
15
15
  export * from './corestorereplication.js';
16
16
  export * from './delegatedadmintoken.js';
17
+ export * from './diskencryption.js';
17
18
  export * from './coremail.js';
18
19
  export * from './coremail.runtime.js';
19
20
  export * from './deployment.js';
@@ -104,6 +105,7 @@ export * from './serviceports.js';
104
105
  export * from './serviceruntime.js';
105
106
  export * from './launchersecretowner.js';
106
107
  export * from './location.js';
108
+ export * from './locationlock.js';
107
109
  export * from './log.js';
108
110
  export * from './servicevolumeinitialization.js';
109
111
  export * from './status.js';
@@ -0,0 +1,280 @@
1
+ import { validateControllerIdentifier, validateControllerStrictJson } from '../private/controllercontract.js';
2
+ import { hasExactKeys, readDataElements, readDataProperties, readExactDataRecord } from '../private/dataproperties.js';
3
+ import { isClusterNodeId } from '../private/nodeidentifier.js';
4
+ import { isBoundedInteger } from '../private/runtimepolicy.js';
5
+ import { validateServiceId } from './coremail.runtime.js';
6
+ import { isSha256Digest, type TSha256Digest } from './immutableimage.js';
7
+ import { isLocationMemberKind, isLocationName, type ILocationMember } from './location.js';
8
+
9
+ const lockModes = ['lock-now', 'evacuate-then-lock'] as const;
10
+ const lockPhases = [
11
+ 'recorded', 'locking-machines', 'promoting-peer', 'activating-fast-services', 'self-locking', 'locked', 'unlocked',
12
+ ] as const;
13
+ const machineStatuses = ['pending', 'confirmed', 'unreachable', 'self-demoting', 'edge-revoked'] as const;
14
+ const destroyStatuses = ['pending-confirmation', 'executing', 'destroyed', 'cancelled', 'expired'] as const;
15
+
16
+ export type TLocationLockMode = typeof lockModes[number];
17
+ export type TLocationLockPhase = typeof lockPhases[number];
18
+ export type TLocationLockMachineStatus = typeof machineStatuses[number];
19
+ export type TLocationDestroyStatus = typeof destroyStatuses[number];
20
+
21
+ export const locationLockRefusals = Object.freeze([
22
+ 'location-not-found', 'membership-unconfirmed', 'membership-changed', 'already-locked', 'not-locked',
23
+ 'already-destroyed', 'fresh-passkey-required', 'cloud-access-forbidden', 'same-administrator-forbidden',
24
+ 'destroy-not-found', 'destroy-expired', 'destroy-not-pending', 'lock-not-found', 'conflict', 'request-invalid',
25
+ ] as const);
26
+
27
+ export type TLocationLockRefusal = typeof locationLockRefusals[number];
28
+
29
+ export const locationLockBounds = Object.freeze({
30
+ maximumMachines: 1024,
31
+ maximumServices: 1024,
32
+ maximumSecrets: 1024,
33
+ maximumDetailBytes: 256,
34
+ // A list page carries complete machine snapshots. Keep it under the TypedSocket text frame limit.
35
+ operationsPerPage: 8,
36
+ });
37
+
38
+ export interface ILocationLockMachineState {
39
+ member: ILocationMember;
40
+ status: TLocationLockMachineStatus;
41
+ confirmedAt: number | null;
42
+ lastAttemptAt: number | null;
43
+ /** Bounded diagnostic text. Never include credentials or key material. */
44
+ detail?: string;
45
+ }
46
+
47
+ export interface ILocationLockPlan {
48
+ locationId: string;
49
+ locationName: string;
50
+ membershipDigest: TSha256Digest;
51
+ membershipConfirmed: boolean;
52
+ mode: TLocationLockMode;
53
+ controllerInLocation: boolean;
54
+ edgeOnlyLocation: boolean;
55
+ machines: ILocationMember[];
56
+ fastServiceIds: string[];
57
+ blockingReasons: TLocationLockRefusal[];
58
+ }
59
+
60
+ /** One durable forward-only operation. Times are Unix milliseconds. */
61
+ export interface ILocationLockOperation {
62
+ id: string;
63
+ locationId: string;
64
+ membershipDigest: TSha256Digest;
65
+ mode: TLocationLockMode;
66
+ phase: TLocationLockPhase;
67
+ controllerInLocation: boolean;
68
+ edgeOnlyLocation: boolean;
69
+ machines: ILocationLockMachineState[];
70
+ fastServiceIds: string[];
71
+ fastServicesTriggeredAt: number | null;
72
+ initiatedBy: string;
73
+ initiatedAt: number;
74
+ unlockedBy: string | null;
75
+ unlockedAt: number | null;
76
+ revision: number;
77
+ updatedAt: number;
78
+ }
79
+
80
+ export interface ILocationDestroyPlan {
81
+ locationId: string;
82
+ locationName: string;
83
+ membershipDigest: TSha256Digest;
84
+ membershipConfirmed: boolean;
85
+ locked: boolean;
86
+ controllerInLocation: boolean;
87
+ wrappedKeyCount: number;
88
+ hasOfflineRecoveryKey: boolean;
89
+ credentialsToRevoke: number;
90
+ /** Secret identifiers only. */
91
+ secretsToRotate: string[];
92
+ blockingReasons: TLocationLockRefusal[];
93
+ }
94
+
95
+ /** Irreversible operation. Cloudly verifies direct access and two distinct human administrators. */
96
+ export interface ILocationDestroyOperation {
97
+ id: string;
98
+ locationId: string;
99
+ membershipDigest: TSha256Digest;
100
+ status: TLocationDestroyStatus;
101
+ directOnly: true;
102
+ initiatorActorId: string;
103
+ initiatedAt: number;
104
+ expiresAt: number;
105
+ confirmerActorId: string | null;
106
+ confirmedAt: number | null;
107
+ completedAt: number | null;
108
+ wrappedKeysDestroyed: boolean;
109
+ offlineRecoveryKeyDestroyed: boolean;
110
+ credentialsRevoked: boolean;
111
+ secretsRotated: boolean;
112
+ revision: number;
113
+ }
114
+
115
+ const invalid = (): never => { throw new Error('Location lock and destroy contract rejected.'); };
116
+
117
+ const exact = (value: unknown, keys: readonly string[]) => readExactDataRecord(value, keys) ?? invalid();
118
+ const identifier = (value: unknown): string =>
119
+ typeof value === 'string' && validateControllerIdentifier(value, 'identifier').length === 0 ? value : invalid();
120
+ const integer = (value: unknown, minimum: number): number =>
121
+ isBoundedInteger(value, minimum, Number.MAX_SAFE_INTEGER) ? value : invalid();
122
+ const timestamp = (value: unknown): number | null => value === null ? null : integer(value, 1);
123
+ const booleanOf = (value: unknown): boolean => typeof value === 'boolean' ? value : invalid();
124
+ const digest = (value: unknown): TSha256Digest =>
125
+ typeof value === 'string' && isSha256Digest(value) ? value : invalid();
126
+ const choice = <T extends string>(value: unknown, choices: readonly T[]): T =>
127
+ choices.find((candidate) => candidate === value) ?? invalid();
128
+
129
+ const uniqueList = <T>(
130
+ value: unknown, maximum: number, snapshot: (entry: unknown) => T, keyOf: (entry: T) => string,
131
+ ): T[] => {
132
+ const entries = (readDataElements(value, maximum) ?? invalid()).map(snapshot);
133
+ if (new Set(entries.map(keyOf)).size !== entries.length) return invalid();
134
+ return entries;
135
+ };
136
+
137
+ const memberOf = (value: unknown): ILocationMember => {
138
+ const member = exact(value, ['kind', 'id']);
139
+ const { kind, id } = member;
140
+ if (!isLocationMemberKind(kind)) return invalid();
141
+ return { kind, id: kind === 'node' ? (isClusterNodeId(id) ? id : invalid()) : identifier(id) };
142
+ };
143
+
144
+ const memberKey = ({ kind, id }: ILocationMember): string => kind + ':' + id;
145
+ const serviceIdOf = (value: unknown): string =>
146
+ typeof value === 'string' && validateServiceId(value).length === 0 ? value : invalid();
147
+ const servicesOf = (value: unknown): string[] =>
148
+ uniqueList(value, locationLockBounds.maximumServices, serviceIdOf, (id) => id);
149
+
150
+ export const snapshotLocationLockRefusal = (value: unknown): TLocationLockRefusal => choice(value, locationLockRefusals);
151
+
152
+ const planKeys = [
153
+ 'locationId', 'locationName', 'membershipDigest', 'membershipConfirmed', 'controllerInLocation', 'blockingReasons',
154
+ ] as const;
155
+
156
+ const planOf = (plan: Record<string, unknown>) => ({
157
+ locationId: identifier(plan.locationId),
158
+ locationName: isLocationName(plan.locationName) ? plan.locationName : invalid(),
159
+ membershipDigest: digest(plan.membershipDigest),
160
+ membershipConfirmed: booleanOf(plan.membershipConfirmed),
161
+ controllerInLocation: booleanOf(plan.controllerInLocation),
162
+ blockingReasons: uniqueList(
163
+ plan.blockingReasons, locationLockRefusals.length, snapshotLocationLockRefusal, (code) => code,
164
+ ),
165
+ });
166
+
167
+ const machineStateKeys = ['member', 'status', 'confirmedAt', 'lastAttemptAt'] as const;
168
+ const encoder = new TextEncoder();
169
+
170
+ export const snapshotLocationLockMachineState = (value: unknown): ILocationLockMachineState => {
171
+ const state = readDataProperties(value) ?? invalid();
172
+ if (!hasExactKeys(state, machineStateKeys, ['detail'])) return invalid();
173
+ const snapshot = {
174
+ member: memberOf(state.member),
175
+ status: choice(state.status, machineStatuses),
176
+ confirmedAt: timestamp(state.confirmedAt),
177
+ lastAttemptAt: timestamp(state.lastAttemptAt),
178
+ };
179
+ if (!Object.hasOwn(state, 'detail')) return snapshot;
180
+ const { detail } = state;
181
+ const limit = locationLockBounds.maximumDetailBytes;
182
+ if (typeof detail !== 'string' || detail.length > limit || /[\u0000-\u001f\u007f-\u009f]/u.test(detail)
183
+ || encoder.encode(detail).length > limit || validateControllerStrictJson(detail, 'detail').length !== 0) return invalid();
184
+ return { ...snapshot, detail };
185
+ };
186
+
187
+ export const snapshotLocationLockPlan = (value: unknown): ILocationLockPlan => {
188
+ const plan = exact(value, [...planKeys, 'mode', 'edgeOnlyLocation', 'machines', 'fastServiceIds']);
189
+ return {
190
+ ...planOf(plan),
191
+ mode: choice(plan.mode, lockModes),
192
+ edgeOnlyLocation: booleanOf(plan.edgeOnlyLocation),
193
+ machines: uniqueList(plan.machines, locationLockBounds.maximumMachines, memberOf, memberKey),
194
+ fastServiceIds: servicesOf(plan.fastServiceIds),
195
+ };
196
+ };
197
+
198
+ export const snapshotLocationLockOperation = (value: unknown): ILocationLockOperation => {
199
+ const operation = exact(value, [
200
+ 'id', 'locationId', 'membershipDigest', 'mode', 'phase', 'controllerInLocation', 'edgeOnlyLocation', 'machines',
201
+ 'fastServiceIds', 'fastServicesTriggeredAt', 'initiatedBy', 'initiatedAt', 'unlockedBy', 'unlockedAt', 'revision',
202
+ 'updatedAt',
203
+ ]);
204
+ const phase = choice(operation.phase, lockPhases);
205
+ const initiatedAt = integer(operation.initiatedAt, 1);
206
+ const updatedAt = integer(operation.updatedAt, initiatedAt);
207
+ const fastServicesTriggeredAt = timestamp(operation.fastServicesTriggeredAt);
208
+ const unlockedBy = operation.unlockedBy === null ? null : identifier(operation.unlockedBy);
209
+ const unlockedAt = timestamp(operation.unlockedAt);
210
+ if ((phase === 'unlocked') !== (unlockedBy !== null) || (phase === 'unlocked') !== (unlockedAt !== null)) {
211
+ return invalid();
212
+ }
213
+ const machines = uniqueList(
214
+ operation.machines, locationLockBounds.maximumMachines, snapshotLocationLockMachineState, (state) => memberKey(state.member),
215
+ );
216
+ const withinOperation = (time: number | null) => time === null || (time >= initiatedAt && time <= updatedAt);
217
+ if (!withinOperation(fastServicesTriggeredAt) || !withinOperation(unlockedAt)
218
+ || machines.some(({ confirmedAt, lastAttemptAt }) => !withinOperation(confirmedAt) || !withinOperation(lastAttemptAt))) {
219
+ return invalid();
220
+ }
221
+ return {
222
+ id: identifier(operation.id), locationId: identifier(operation.locationId), membershipDigest: digest(operation.membershipDigest),
223
+ mode: choice(operation.mode, lockModes), phase,
224
+ controllerInLocation: booleanOf(operation.controllerInLocation), edgeOnlyLocation: booleanOf(operation.edgeOnlyLocation),
225
+ machines, fastServiceIds: servicesOf(operation.fastServiceIds), fastServicesTriggeredAt,
226
+ initiatedBy: identifier(operation.initiatedBy), initiatedAt, unlockedBy, unlockedAt,
227
+ revision: integer(operation.revision, 1), updatedAt,
228
+ };
229
+ };
230
+
231
+ export const snapshotLocationDestroyPlan = (value: unknown): ILocationDestroyPlan => {
232
+ const plan = exact(value, [
233
+ ...planKeys, 'locked', 'wrappedKeyCount', 'hasOfflineRecoveryKey', 'credentialsToRevoke', 'secretsToRotate',
234
+ ]);
235
+ return {
236
+ ...planOf(plan),
237
+ locked: booleanOf(plan.locked),
238
+ wrappedKeyCount: integer(plan.wrappedKeyCount, 0),
239
+ hasOfflineRecoveryKey: booleanOf(plan.hasOfflineRecoveryKey),
240
+ credentialsToRevoke: integer(plan.credentialsToRevoke, 0),
241
+ secretsToRotate: uniqueList(plan.secretsToRotate, locationLockBounds.maximumSecrets, identifier, (id) => id),
242
+ };
243
+ };
244
+
245
+ export const snapshotLocationDestroyOperation = (value: unknown): ILocationDestroyOperation => {
246
+ const operation = exact(value, [
247
+ 'id', 'locationId', 'membershipDigest', 'status', 'directOnly', 'initiatorActorId', 'initiatedAt', 'expiresAt',
248
+ 'confirmerActorId', 'confirmedAt', 'completedAt', 'wrappedKeysDestroyed', 'offlineRecoveryKeyDestroyed',
249
+ 'credentialsRevoked', 'secretsRotated', 'revision',
250
+ ]);
251
+ if (operation.directOnly !== true) return invalid();
252
+ const status = choice(operation.status, destroyStatuses);
253
+ const initiatorActorId = identifier(operation.initiatorActorId);
254
+ const confirmerActorId = operation.confirmerActorId === null ? null : identifier(operation.confirmerActorId);
255
+ if (confirmerActorId === initiatorActorId) return invalid();
256
+
257
+ const initiatedAt = integer(operation.initiatedAt, 1);
258
+ const expiresAt = integer(operation.expiresAt, 1);
259
+ const confirmedAt = timestamp(operation.confirmedAt);
260
+ const completedAt = timestamp(operation.completedAt);
261
+ const authorized = status === 'executing' || status === 'destroyed';
262
+ if (expiresAt <= initiatedAt || authorized !== (confirmerActorId !== null) || authorized !== (confirmedAt !== null)
263
+ || (confirmedAt !== null && (confirmedAt < initiatedAt || confirmedAt >= expiresAt))
264
+ || (status === 'destroyed' && completedAt === null) || (status === 'executing' && completedAt !== null)
265
+ || (status === 'pending-confirmation' && completedAt !== null)
266
+ || (completedAt !== null && completedAt < (confirmedAt ?? initiatedAt))) return invalid();
267
+
268
+ const progress = {
269
+ wrappedKeysDestroyed: booleanOf(operation.wrappedKeysDestroyed),
270
+ offlineRecoveryKeyDestroyed: booleanOf(operation.offlineRecoveryKeyDestroyed),
271
+ credentialsRevoked: booleanOf(operation.credentialsRevoked),
272
+ secretsRotated: booleanOf(operation.secretsRotated),
273
+ };
274
+ if (!authorized && Object.values(progress).some(Boolean)) return invalid();
275
+ return {
276
+ id: identifier(operation.id), locationId: identifier(operation.locationId), membershipDigest: digest(operation.membershipDigest),
277
+ status, directOnly: true, initiatorActorId, initiatedAt, expiresAt, confirmerActorId, confirmedAt, completedAt,
278
+ ...progress, revision: integer(operation.revision, 1),
279
+ };
280
+ };