@serve.zone/interfaces 32.115.0 → 32.116.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,338 @@
1
+ import { compareWireTokens } from '../private/canonicaljson.js';
2
+ import { validateControllerIdentifier, validateControllerStrictJson } from '../private/controllercontract.js';
3
+ import { readDataElements, readExactDataRecord } from '../private/dataproperties.js';
4
+ import { isBoundedInteger } from '../private/runtimepolicy.js';
5
+ import { validateServiceId } from './coremail.runtime.js';
6
+ import { isIdempotencyKey } from './idempotencykey.js';
7
+
8
+ export const controlledTakeoverPhases = Object.freeze([
9
+ 'pending', 'promotingController', 'drainingServices', 'completed', 'failed', 'aborted',
10
+ ] as const);
11
+ export type TControlledTakeoverPhase = typeof controlledTakeoverPhases[number];
12
+
13
+ export type TControlledTakeoverTrigger = 'operator' | 'nupst';
14
+
15
+ export const controlledTakeoverServicePhases = Object.freeze([
16
+ 'pending', 'stopping', 'syncing', 'activating', 'completed', 'skipped', 'failed',
17
+ ] as const);
18
+ export type TControlledTakeoverServicePhase = typeof controlledTakeoverServicePhases[number];
19
+
20
+ export const controlledTakeoverBounds = Object.freeze({
21
+ maximumServices: 1024,
22
+ maximumServiceNameBytes: 256,
23
+ maximumRefusalCodeLength: 64,
24
+ // Each operation carries the full service plan. Keep full pages below the 16 MiB text frame.
25
+ operationsPerPage: 8,
26
+ });
27
+
28
+ export interface IControlledTakeoverServiceEntry {
29
+ serviceId: string;
30
+ serviceName: string;
31
+ isIngress: boolean;
32
+ priority: number;
33
+ phase: TControlledTakeoverServicePhase;
34
+ /** Unix milliseconds. Null until the service starts moving. */
35
+ startedAt: number | null;
36
+ /** Unix milliseconds. Null until the service reaches a terminal phase. */
37
+ completedAt: number | null;
38
+ /** A machine-readable code for a skipped or failed service. */
39
+ refusalCode: string | null;
40
+ }
41
+
42
+ /** Durable observation of one forward-only move. Timestamps are Unix milliseconds. */
43
+ export interface IControlledTakeoverOperation {
44
+ id: string;
45
+ sourceClusterId: string;
46
+ targetClusterId: string;
47
+ sourceLocationId: string;
48
+ targetLocationId: string;
49
+ trigger: TControlledTakeoverTrigger;
50
+ /** The authenticated nupst webhook-id. An operator start has no delivery ID. */
51
+ nupstDeliveryId: string | null;
52
+ executeAt: number;
53
+ deadlineAt: number;
54
+ safetyMarginMs: number;
55
+ phase: TControlledTakeoverPhase;
56
+ revision: number;
57
+ createdAt: number;
58
+ updatedAt: number;
59
+ completedAt: number | null;
60
+ /** In the controller's execution order, with ingress services first. */
61
+ services: IControlledTakeoverServiceEntry[];
62
+ /** A machine-readable code for a failed operation. */
63
+ failureReason: string | null;
64
+ }
65
+
66
+ /** Webhook endpoint metadata. Cloudly owns secret presence, version and rotation. */
67
+ export interface INupstWebhookEndpointConfig {
68
+ id: string;
69
+ locationId: string;
70
+ clusterId: string;
71
+ enabled: boolean;
72
+ secretConfigured: boolean;
73
+ secretVersion: number | null;
74
+ safetyMarginMs: number;
75
+ updatedAt: number;
76
+ }
77
+
78
+ export interface IControlledTakeoverStartInput {
79
+ sourceClusterId: string;
80
+ targetClusterId: string;
81
+ /** Operator-supplied shutdown time in Unix milliseconds. */
82
+ executeAt: number;
83
+ safetyMarginMs: number;
84
+ /** Stable across retries of a single operator start. */
85
+ idempotencyKey: string;
86
+ }
87
+
88
+ export interface IControlledTakeoverGetInput {
89
+ operationId: string;
90
+ }
91
+
92
+ export interface IControlledTakeoverListInput {
93
+ /** Exclusive operation ID cursor. Null requests the first page. */
94
+ after: string | null;
95
+ }
96
+
97
+ export interface IControlledTakeoverAbortInput extends IControlledTakeoverGetInput {
98
+ expectedRevision: number;
99
+ }
100
+
101
+ export interface INupstWebhookEndpointConfigureInput {
102
+ id: string;
103
+ locationId: string;
104
+ clusterId: string;
105
+ enabled: boolean;
106
+ safetyMarginMs: number;
107
+ }
108
+
109
+ export interface INupstWebhookEndpointRotateInput {
110
+ id: string;
111
+ /** Null requires that a secret has yet to be provisioned. */
112
+ expectedSecretVersion: number | null;
113
+ }
114
+
115
+ export interface IControlledTakeoverOperationResponse {
116
+ operation: IControlledTakeoverOperation;
117
+ }
118
+
119
+ export interface IControlledTakeoverListResponse {
120
+ /** Strictly ascending by operation ID. */
121
+ operations: IControlledTakeoverOperation[];
122
+ /** The last returned ID if another page exists. Null at the end. */
123
+ nextAfter: string | null;
124
+ }
125
+
126
+ export const controlledTakeoverAbortRefusals = Object.freeze([
127
+ 'operation-not-found', 'revision-stale', 'operation-not-abortable',
128
+ ] as const);
129
+ export type TControlledTakeoverAbortRefusal = typeof controlledTakeoverAbortRefusals[number];
130
+
131
+ export type TControlledTakeoverAbortResponse =
132
+ | { ok: true; operation: IControlledTakeoverOperation }
133
+ | { ok: false; code: TControlledTakeoverAbortRefusal };
134
+
135
+ export interface INupstWebhookEndpointResponse {
136
+ endpoint: INupstWebhookEndpointConfig;
137
+ }
138
+
139
+ const invalid = (): never => { throw new Error('Controlled takeover contract rejected.'); };
140
+ const exact = (value: unknown, keys: readonly string[]) => readExactDataRecord(value, keys) ?? invalid();
141
+ const identifier = (value: unknown): string =>
142
+ typeof value === 'string' && validateControllerIdentifier(value, 'identifier').length === 0 ? value : invalid();
143
+ const integer = (value: unknown, minimum: number): number =>
144
+ isBoundedInteger(value, minimum, Number.MAX_SAFE_INTEGER) ? value : invalid();
145
+ const nullablePositive = (value: unknown): number | null => value === null ? null : integer(value, 1);
146
+ const boolean = (value: unknown): boolean => typeof value === 'boolean' ? value : invalid();
147
+ const choice = <T extends string>(value: unknown, choices: readonly T[]): T =>
148
+ choices.find((candidate) => candidate === value) ?? invalid();
149
+
150
+ const encoder = new TextEncoder();
151
+ const serviceNameOf = (value: unknown): string => {
152
+ if (typeof value !== 'string' || value.length === 0 || value.length > controlledTakeoverBounds.maximumServiceNameBytes
153
+ || /[\u0000-\u001f\u007f-\u009f]/u.test(value) || encoder.encode(value).byteLength > controlledTakeoverBounds.maximumServiceNameBytes
154
+ || validateControllerStrictJson(value, 'serviceName').length !== 0) return invalid();
155
+ return value;
156
+ };
157
+
158
+ const reasonCodeOf = (value: unknown): string | null => {
159
+ if (value === null) return null;
160
+ if (typeof value !== 'string' || value.length > controlledTakeoverBounds.maximumRefusalCodeLength
161
+ || !/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(value)) return invalid();
162
+ return value;
163
+ };
164
+
165
+ /** Capture one service observation with phase-dependent timestamps and refusal code. */
166
+ export const snapshotControlledTakeoverServiceEntry = (value: unknown): IControlledTakeoverServiceEntry => {
167
+ const entry = exact(value, ['serviceId', 'serviceName', 'isIngress', 'priority', 'phase', 'startedAt', 'completedAt', 'refusalCode']);
168
+ const { serviceId } = entry;
169
+ if (typeof serviceId !== 'string' || validateServiceId(serviceId).length !== 0) return invalid();
170
+
171
+ const phase = choice(entry.phase, controlledTakeoverServicePhases);
172
+ const startedAt = nullablePositive(entry.startedAt);
173
+ const completedAt = nullablePositive(entry.completedAt);
174
+ const refusalCode = reasonCodeOf(entry.refusalCode);
175
+ const terminal = phase === 'completed' || phase === 'failed' || phase === 'skipped';
176
+ const refused = phase === 'failed' || phase === 'skipped';
177
+
178
+ if (terminal !== (completedAt !== null) || refused !== (refusalCode !== null)) return invalid();
179
+ if (phase === 'pending' || phase === 'skipped') {
180
+ if (startedAt !== null) return invalid();
181
+ } else if (phase !== 'failed' && startedAt === null) return invalid();
182
+ if (startedAt !== null && completedAt !== null && startedAt > completedAt) return invalid();
183
+
184
+ return {
185
+ serviceId, serviceName: serviceNameOf(entry.serviceName), isIngress: boolean(entry.isIngress),
186
+ priority: integer(entry.priority, Number.MIN_SAFE_INTEGER), phase, startedAt, completedAt, refusalCode,
187
+ };
188
+ };
189
+
190
+ const scheduleOf = (record: Record<string, unknown>) => {
191
+ const executeAt = integer(record.executeAt, 1);
192
+ const safetyMarginMs = integer(record.safetyMarginMs, 0);
193
+ if (safetyMarginMs >= executeAt) return invalid();
194
+ return { executeAt, safetyMarginMs };
195
+ };
196
+
197
+ const clustersOf = (record: Record<string, unknown>) => {
198
+ const sourceClusterId = identifier(record.sourceClusterId);
199
+ const targetClusterId = identifier(record.targetClusterId);
200
+ if (sourceClusterId === targetClusterId) return invalid();
201
+ return { sourceClusterId, targetClusterId };
202
+ };
203
+
204
+ /** Capture a value-free operation snapshot. Fencing and transition admission belong to Cloudly. */
205
+ export const snapshotControlledTakeoverOperation = (value: unknown): IControlledTakeoverOperation => {
206
+ const operation = exact(value, [
207
+ 'id', 'sourceClusterId', 'targetClusterId', 'sourceLocationId', 'targetLocationId', 'trigger',
208
+ 'nupstDeliveryId', 'executeAt', 'deadlineAt', 'safetyMarginMs', 'phase', 'revision', 'createdAt',
209
+ 'updatedAt', 'completedAt', 'services', 'failureReason',
210
+ ]);
211
+ const id = identifier(operation.id);
212
+ const clusters = clustersOf(operation);
213
+ const sourceLocationId = identifier(operation.sourceLocationId);
214
+ const targetLocationId = identifier(operation.targetLocationId);
215
+ if (sourceLocationId === targetLocationId) return invalid();
216
+
217
+ const trigger = choice(operation.trigger, ['operator', 'nupst'] as const);
218
+ const nupstDeliveryId = operation.nupstDeliveryId === null ? null : identifier(operation.nupstDeliveryId);
219
+ if ((trigger === 'nupst') !== (nupstDeliveryId !== null)) return invalid();
220
+
221
+ const schedule = scheduleOf(operation);
222
+ const deadlineAt = integer(operation.deadlineAt, 1);
223
+ if (deadlineAt !== schedule.executeAt - schedule.safetyMarginMs) return invalid();
224
+
225
+ const phase = choice(operation.phase, controlledTakeoverPhases);
226
+ const revision = integer(operation.revision, 1);
227
+ const createdAt = integer(operation.createdAt, 1);
228
+ const updatedAt = integer(operation.updatedAt, createdAt);
229
+ const completedAt = nullablePositive(operation.completedAt);
230
+ const failureReason = reasonCodeOf(operation.failureReason);
231
+ const terminal = phase === 'completed' || phase === 'failed' || phase === 'aborted';
232
+ if (terminal !== (completedAt !== null) || (phase === 'failed') !== (failureReason !== null)) return invalid();
233
+ if (completedAt !== null && (completedAt < createdAt || completedAt > updatedAt)) return invalid();
234
+
235
+ const entries = readDataElements(operation.services, controlledTakeoverBounds.maximumServices) ?? invalid();
236
+ const services = entries.map(snapshotControlledTakeoverServiceEntry);
237
+ const serviceIds = new Set<string>();
238
+ let sawNonIngress = false;
239
+ for (const service of services) {
240
+ if (serviceIds.has(service.serviceId) || (service.isIngress && sawNonIngress)) return invalid();
241
+ serviceIds.add(service.serviceId);
242
+ sawNonIngress ||= !service.isIngress;
243
+ for (const time of [service.startedAt, service.completedAt]) {
244
+ if (time !== null && (time < createdAt || time > (completedAt ?? updatedAt))) return invalid();
245
+ }
246
+ }
247
+
248
+ return {
249
+ id, ...clusters, sourceLocationId, targetLocationId, trigger, nupstDeliveryId, ...schedule,
250
+ deadlineAt, phase, revision, createdAt, updatedAt, completedAt, services, failureReason,
251
+ };
252
+ };
253
+
254
+ export const snapshotNupstWebhookEndpointConfig = (value: unknown): INupstWebhookEndpointConfig => {
255
+ const endpoint = exact(value, [
256
+ 'id', 'locationId', 'clusterId', 'enabled', 'secretConfigured', 'secretVersion', 'safetyMarginMs', 'updatedAt',
257
+ ]);
258
+ const secretConfigured = boolean(endpoint.secretConfigured);
259
+ const secretVersion = nullablePositive(endpoint.secretVersion);
260
+ if (secretConfigured !== (secretVersion !== null)) return invalid();
261
+ return {
262
+ id: identifier(endpoint.id), locationId: identifier(endpoint.locationId), clusterId: identifier(endpoint.clusterId),
263
+ enabled: boolean(endpoint.enabled), secretConfigured, secretVersion,
264
+ safetyMarginMs: integer(endpoint.safetyMarginMs, 0), updatedAt: integer(endpoint.updatedAt, 1),
265
+ };
266
+ };
267
+
268
+ export const snapshotControlledTakeoverStartInput = (value: unknown): IControlledTakeoverStartInput => {
269
+ const input = exact(value, ['sourceClusterId', 'targetClusterId', 'executeAt', 'safetyMarginMs', 'idempotencyKey']);
270
+ const { idempotencyKey } = input;
271
+ if (!isIdempotencyKey(idempotencyKey)) return invalid();
272
+ return { ...clustersOf(input), ...scheduleOf(input), idempotencyKey };
273
+ };
274
+
275
+ export const snapshotControlledTakeoverGetInput = (value: unknown): IControlledTakeoverGetInput => {
276
+ const input = exact(value, ['operationId']);
277
+ return { operationId: identifier(input.operationId) };
278
+ };
279
+
280
+ export const snapshotControlledTakeoverListInput = (value: unknown): IControlledTakeoverListInput => {
281
+ const input = exact(value, ['after']);
282
+ return { after: input.after === null ? null : identifier(input.after) };
283
+ };
284
+
285
+ export const snapshotControlledTakeoverAbortInput = (value: unknown): IControlledTakeoverAbortInput => {
286
+ const input = exact(value, ['operationId', 'expectedRevision']);
287
+ return { operationId: identifier(input.operationId), expectedRevision: integer(input.expectedRevision, 1) };
288
+ };
289
+
290
+ export const snapshotNupstWebhookEndpointConfigureInput = (value: unknown): INupstWebhookEndpointConfigureInput => {
291
+ const input = exact(value, ['id', 'locationId', 'clusterId', 'enabled', 'safetyMarginMs']);
292
+ return {
293
+ id: identifier(input.id), locationId: identifier(input.locationId), clusterId: identifier(input.clusterId),
294
+ enabled: boolean(input.enabled), safetyMarginMs: integer(input.safetyMarginMs, 0),
295
+ };
296
+ };
297
+
298
+ export const snapshotNupstWebhookEndpointRotateInput = (value: unknown): INupstWebhookEndpointRotateInput => {
299
+ const input = exact(value, ['id', 'expectedSecretVersion']);
300
+ return { id: identifier(input.id), expectedSecretVersion: nullablePositive(input.expectedSecretVersion) };
301
+ };
302
+
303
+ export const snapshotControlledTakeoverOperationResponse = (value: unknown): IControlledTakeoverOperationResponse => ({
304
+ operation: snapshotControlledTakeoverOperation(exact(value, ['operation']).operation),
305
+ });
306
+
307
+ export const snapshotControlledTakeoverListResponse = (
308
+ value: unknown, request: IControlledTakeoverListInput,
309
+ ): IControlledTakeoverListResponse => {
310
+ const response = exact(value, ['operations', 'nextAfter']);
311
+ const entries = readDataElements(response.operations, controlledTakeoverBounds.operationsPerPage) ?? invalid();
312
+ const operations = entries.map(snapshotControlledTakeoverOperation);
313
+ let lastId = snapshotControlledTakeoverListInput(request).after;
314
+ for (const operation of operations) {
315
+ if (lastId !== null && compareWireTokens(lastId, operation.id) >= 0) return invalid();
316
+ lastId = operation.id;
317
+ }
318
+ const nextAfter = response.nextAfter === null ? null : identifier(response.nextAfter);
319
+ if (nextAfter !== null && (operations.length !== controlledTakeoverBounds.operationsPerPage
320
+ || nextAfter !== lastId)) return invalid();
321
+ return { operations, nextAfter };
322
+ };
323
+
324
+ export const snapshotControlledTakeoverAbortResponse = (value: unknown): TControlledTakeoverAbortResponse => {
325
+ const success = readExactDataRecord(value, ['ok', 'operation']);
326
+ if (success?.ok === true) {
327
+ const operation = snapshotControlledTakeoverOperation(success.operation);
328
+ if (operation.phase !== 'aborted') return invalid();
329
+ return { ok: true, operation };
330
+ }
331
+ const refusal = exact(value, ['ok', 'code']);
332
+ if (refusal.ok !== false) return invalid();
333
+ return { ok: false, code: choice(refusal.code, controlledTakeoverAbortRefusals) };
334
+ };
335
+
336
+ export const snapshotNupstWebhookEndpointResponse = (value: unknown): INupstWebhookEndpointResponse => ({
337
+ endpoint: snapshotNupstWebhookEndpointConfig(exact(value, ['endpoint']).endpoint),
338
+ });
@@ -8,10 +8,12 @@
8
8
  * A row is addressed by area, member and id: a list member's row by its `id`, a singleton member
9
9
  * (`gatewayAreaSingletonMembers`) by `id: null`. Its write form (`IGatewayAreaRowWrites`) is its
10
10
  * table type (`gatewayareas.ts`) except that every secret-class member (`gatewayAreaSecretPaths`) is
11
- * a keep-or-set choice: a read answers every secret as `keep` (a sealed member with its version, a
11
+ * a keep-or-set choice, with an explicit promotion for the active edge secret. A read answers
12
+ * every secret as `keep` (a sealed member with its version, a
12
13
  * verifier without anything), so a row read and sent back unchanged writes nothing, and a write
13
14
  * states a new secret only as `set`. A sealed value's version is minted by the controller that
14
15
  * resolves the write (Linus ruling 121 Q9: by every write that sets a secret), never by the request.
16
+ * Promotion preserves the version of the staged secret it moves.
15
17
  * Nothing here carries a stored secret value: reads and answers name versions, never values.
16
18
  *
17
19
  * Both requests are for a human administrator who signed in within the last five minutes, with
@@ -84,6 +86,9 @@ export type TGatewaySealedValueWrite =
84
86
  /** A new value; the controller mints its version. */
85
87
  | { kind: 'set'; value: string };
86
88
 
89
+ /** Moves the observed staged version into the active slot and clears the staged slot. */
90
+ export type TGatewayEdgeSecretWrite = TGatewaySealedValueWrite | { kind: 'promoteStaged'; version: string };
91
+
87
92
  /** A verifier member in a row's write form; the secret it verifies never travels. */
88
93
  export type TGatewayVerifierWrite<TVerifier> =
89
94
  /**
@@ -152,14 +157,17 @@ export interface IGatewayCoreMailPeerRowWrite extends Omit<IGatewayCoreMailPeerR
152
157
  credentials: TGatewayVerifierWrite<IGatewayCoreMailCredentialVerifier[]>;
153
158
  }
154
159
 
155
- /** `IGatewayEdgeRow` with its tunnel secrets as keep-or-set choices. */
160
+ /** `IGatewayEdgeRow` in write form. A `promoteStaged` active secret requires `stagedSecret: null`. */
156
161
  export interface IGatewayEdgeRowWrite extends Omit<IGatewayEdgeRow, 'secret' | 'stagedSecret'> {
157
- secret: TGatewaySealedValueWrite;
162
+ secret: TGatewayEdgeSecretWrite;
158
163
  stagedSecret: TGatewaySealedValueWrite | null;
159
164
  }
160
165
 
161
166
  /** The row write form for an edge that still uses the pre-rotation table shape. */
162
- export type TGatewayLegacyEdgeRowWrite = Omit<IGatewayEdgeRowWrite, 'stagedSecret'> & { stagedSecret?: never };
167
+ export type TGatewayLegacyEdgeRowWrite = Omit<IGatewayEdgeRowWrite, 'secret' | 'stagedSecret'> & {
168
+ secret: TGatewaySealedValueWrite;
169
+ stagedSecret?: never;
170
+ };
163
171
 
164
172
  /**
165
173
  * The write form of one row of every member, by area and member: a list member's row, or a
@@ -325,6 +333,7 @@ const failRowDigest = (reasonArg: string): never => {
325
333
  * input (the read answers the row and the versions) cannot test a guess at a sealed value against
326
334
  * it. Throws, naming no value, for an unknown area or member, an `id` that is not `null` exactly
327
335
  * for a singleton, and a row that is not strict JSON or lacks a required sealed member or its version.
336
+ * A promotion write form must be resolved before computing the stored row's token.
328
337
  * Legacy edges rows have no `stagedSecret` member and retain their original digest input.
329
338
  */
330
339
  export const createGatewayAreaRowDigestInput = (inputArg: {
@@ -338,8 +347,11 @@ export const createGatewayAreaRowDigestInput = (inputArg: {
338
347
  if ((id === null) !== isGatewayAreaSingletonMember(area, member)) failRowDigest(`${area} ${member} takes ${id === null ? 'a row id' : 'id null'}`);
339
348
  const row = (copyStrictJson(inputArg.row) ?? failRowDigest(`the ${area} ${member} row is not strict JSON`)).value;
340
349
  for (const secret of secretPathsOf(area, member)) {
341
- if (secret.secretClass !== 'sealed') continue;
342
350
  const place = parentOf(row, splitPath(secret.path));
351
+ if (place !== null && readDataProperty(place.parent[place.key], 'kind')?.value === 'promoteStaged') {
352
+ failRowDigest(`the ${area} ${member} row's ${secret.path} is an unresolved promotion`);
353
+ }
354
+ if (secret.secretClass !== 'sealed') continue;
343
355
  if (place === null) {
344
356
  if (allowsLegacySecretOmission(area, member, secret.path)) continue;
345
357
  return failRowDigest(`the ${area} ${member} row has no member ${secret.path}`);
@@ -488,21 +500,34 @@ export type TGatewayAreaRowWriteReport =
488
500
  | { ok: true; written: IGatewayAreaRowWritten }
489
501
  | { ok: false; code: TGatewayAreaRowWriteRefusal; problems: string[] };
490
502
 
491
- /** One secret member of a write form as written: `null`, a keep or a set; `null` itself for a malformed form. */
503
+ /** One parsed secret write choice. `null` itself denotes a malformed form. */
492
504
  type TSecretWriteForm =
493
505
  | { form: 'null' }
494
506
  | { form: 'keep'; version: string | null }
507
+ | { form: 'promoteStaged'; version: string }
495
508
  | { form: 'set'; value: unknown };
496
509
 
497
- const readSecretWriteForm = (valueArg: unknown, secretClassArg: TGatewayAreaSecretClass): TSecretWriteForm | null => {
510
+ const permitsStagedPromotion = (
511
+ areaArg: TGatewayConfigArea, memberArg: string, pathArg: string, rowArg: unknown,
512
+ ): boolean => areaArg === 'edges' && memberArg === 'edges' && pathArg === 'secret'
513
+ && readDataProperty(rowArg, 'stagedSecret')?.value === null;
514
+
515
+ const readSecretWriteForm = (
516
+ valueArg: unknown, secretClassArg: TGatewayAreaSecretClass, permitsPromotionArg: boolean,
517
+ ): TSecretWriteForm | null => {
498
518
  if (valueArg === null) return { form: 'null' };
499
519
  if (secretClassArg === 'verifier') {
500
520
  if (readExactDataRecord(valueArg, ['kind'])?.kind === 'keep') return { form: 'keep', version: null };
501
521
  const set = readExactDataRecord(valueArg, ['kind', 'verifier']);
502
522
  return set?.kind === 'set' ? { form: 'set', value: set.verifier } : null;
503
523
  }
504
- const keep = readExactDataRecord(valueArg, ['kind', 'version']);
505
- if (keep?.kind === 'keep' && typeof keep.version === 'string') return { form: 'keep', version: keep.version };
524
+ const choice = readExactDataRecord(valueArg, ['kind', 'version']);
525
+ if (choice !== null && typeof choice.version === 'string') {
526
+ if (choice.kind === 'keep') return { form: 'keep', version: choice.version };
527
+ if (choice.kind === 'promoteStaged' && permitsPromotionArg) {
528
+ return { form: 'promoteStaged', version: choice.version };
529
+ }
530
+ }
506
531
  const set = readExactDataRecord(valueArg, ['kind', 'value']);
507
532
  return set?.kind === 'set' && typeof set.value === 'string' ? { form: 'set', value: set.value } : null;
508
533
  };
@@ -538,7 +563,8 @@ const rowWriteKeys = Object.freeze({
538
563
  * deleted) and a row id (`isGatewayAreaRowId`) for a list member, a `sha256:` `expectedDigest`
539
564
  * (`null` only for a put), and for a put a strict JSON row whose `id` is the address's (a list
540
565
  * member) and whose every secret member (`gatewayAreaSecretPaths`) is `null` or one of its
541
- * keep-or-set forms. A legacy edges row omits `stagedSecret`. A put of a `security` `apiTokens` row
566
+ * keep-or-set forms. Only `edges.edges.secret` may use `promoteStaged`, with an explicit
567
+ * `stagedSecret: null`. A legacy edges row omits `stagedSecret`. A put of a `security` `apiTokens` row
542
568
  * whose policy binds a gateway client (`isGatewayClientBoundApiTokenPolicy`) is refused naming the row (Linus ruling 376
543
569
  * item 6): the controller is the one author of the tables and compiles no gateway-client token, so
544
570
  * such a write would vanish at the next compile and a gateway from dcrouter 35 refuses it. The
@@ -582,8 +608,10 @@ export const validateGatewayAreaRowWrite = (valueArg: unknown, pathArg = 'write'
582
608
  for (const secret of secretPathsOf(area, member)) {
583
609
  const place = parentOf(row, splitPath(secret.path));
584
610
  if (place === null && allowsLegacySecretOmission(area, member, secret.path)) continue;
585
- if (place === null || readSecretWriteForm(place.parent[place.key], secret.secretClass) === null) {
586
- problems.push(`${pathArg} row ${secret.path} must be null or a ${secret.secretClass} keep-or-set form`);
611
+ const permitsPromotion = permitsStagedPromotion(area, member, secret.path, row);
612
+ if (place === null || readSecretWriteForm(place.parent[place.key], secret.secretClass, permitsPromotion) === null) {
613
+ problems.push(`${pathArg} row ${secret.path} must be null or a ${secret.secretClass} keep-or-set form${
614
+ permitsPromotion ? ' or a staged promotion' : ''}`);
587
615
  }
588
616
  }
589
617
  return problems;
@@ -626,8 +654,8 @@ export const projectGatewayAreaRow = <TArea extends TGatewayConfigArea, TMember
626
654
 
627
655
  /**
628
656
  * Why a row's write form cannot be resolved, by the secret's path: `invalid-write-form` for a
629
- * secret member that is not one of its keep-or-set forms (a write `validateGatewayAreaRowWrite`
630
- * refuses), or `kept-secret-unknown` for a `keep` the stored row does not hold there. Never a value.
657
+ * secret member whose write form `validateGatewayAreaRowWrite` refuses, or `kept-secret-unknown`
658
+ * when the stored row lacks the referenced keep or promotion source. Never a value.
631
659
  */
632
660
  export interface IGatewayAreaRowWriteFormRefusal {
633
661
  /** The secret's dotted path inside the row; `''` for the row as a whole. */
@@ -646,7 +674,9 @@ export type TGatewayAreaRowResolution =
646
674
  * when the stored row holds that version there, a verifier `keep` the stored verifier when the row
647
675
  * holds one; a sealed `set` becomes `{ version: mintVersionArg(), value }`, a verifier `set` the
648
676
  * stated verifier; `null` stays `null`. A legacy write can omit `stagedSecret` only when the stored
649
- * row also omits it or the write creates a row. Every other member is copied as written. The area
677
+ * row also omits it or the write creates a row. `promoteStaged` moves the stored staged value and
678
+ * version to the active slot when the version matches, without minting a version. Every other
679
+ * member is copied as written. The area
650
680
  * validator judges the resolved row as part of its table. Judges the forms with the rule
651
681
  * `validateGatewayAreaRowWrite` applies and never reads a value into a refusal. The minted
652
682
  * versions are answered ascending by path. `mintVersionArg` is the writer's
@@ -669,7 +699,8 @@ export const resolveGatewayAreaRowWrite = (inputArg: {
669
699
  const place = parentOf(row, keys);
670
700
  if (place === null && allowsLegacySecretOmission(inputArg.area, inputArg.member, secret.path)
671
701
  && parentOf(inputArg.stored, keys) === null) continue;
672
- const form = place === null ? null : readSecretWriteForm(place.parent[place.key], secret.secretClass);
702
+ const form = place === null ? null : readSecretWriteForm(place.parent[place.key], secret.secretClass,
703
+ permitsStagedPromotion(inputArg.area, inputArg.member, secret.path, row));
673
704
  if (place === null || form === null) {
674
705
  refusals.push({ path: secret.path, code: 'invalid-write-form' });
675
706
  continue;
@@ -685,8 +716,8 @@ export const resolveGatewayAreaRowWrite = (inputArg: {
685
716
  minted.push({ path: secret.path, version });
686
717
  continue;
687
718
  }
688
- const storedPlace = inputArg.stored === null ? null : parentOf(inputArg.stored, keys);
689
- const storedValue = storedPlace === null ? null : storedPlace.parent[storedPlace.key] ?? null;
719
+ const storedPlace = parentOf(inputArg.stored, form.form === 'promoteStaged' ? ['stagedSecret'] : keys);
720
+ const storedValue = storedPlace === null ? null : readDataProperty(storedPlace.parent, storedPlace.key)?.value ?? null;
690
721
  if (secret.secretClass === 'verifier') {
691
722
  if (storedValue === null) refusals.push({ path: secret.path, code: 'kept-secret-unknown' });
692
723
  else place.parent[place.key] = copyStrictJson(storedValue)?.value ?? null;
package/ts/data/index.ts CHANGED
@@ -8,6 +8,7 @@ export * from './clusteringressdesignation.js';
8
8
  export * from './clusterrelaycredential.js';
9
9
  export * from './config.js';
10
10
  export * from './controller.js';
11
+ export * from './controlledtakeover.js';
11
12
  export * from './corestore.js';
12
13
  export * from './corestorecontroltoken.js';
13
14
  export * from './corestorelegacyadoption.js';
package/ts/index.ts CHANGED
@@ -20,3 +20,5 @@ export { dcstorage } from './requests/index.js';
20
20
  export { preparedimages } from './requests/index.js';
21
21
  /** Corestore replication TypedRequest contracts are also available at requests.corestorereplication. */
22
22
  export { corestorereplication } from './requests/index.js';
23
+ /** Controlled takeover TypedRequest contracts are also available at requests.controlledtakeover. */
24
+ export { controlledtakeover } from './requests/index.js';
@@ -0,0 +1,108 @@
1
+ import type * as plugins from '../plugins.js';
2
+ import { readExactDataRecord } from '../private/dataproperties.js';
3
+ import {
4
+ snapshotControlledTakeoverAbortInput,
5
+ snapshotControlledTakeoverGetInput,
6
+ snapshotControlledTakeoverListInput,
7
+ snapshotControlledTakeoverStartInput,
8
+ snapshotNupstWebhookEndpointConfigureInput,
9
+ snapshotNupstWebhookEndpointRotateInput,
10
+ } from '../data/controlledtakeover.js';
11
+ import type {
12
+ IControlledTakeoverAbortInput,
13
+ IControlledTakeoverGetInput,
14
+ IControlledTakeoverListInput,
15
+ IControlledTakeoverListResponse,
16
+ IControlledTakeoverOperationResponse,
17
+ IControlledTakeoverStartInput,
18
+ INupstWebhookEndpointConfigureInput,
19
+ INupstWebhookEndpointResponse,
20
+ INupstWebhookEndpointRotateInput,
21
+ TControlledTakeoverAbortResponse,
22
+ } from '../data/controlledtakeover.js';
23
+ import type { IIdentityCredential } from '../data/user.js';
24
+
25
+ export interface IControlledTakeoverAdminRequest<TInput> {
26
+ identity: IIdentityCredential;
27
+ input: TInput;
28
+ }
29
+
30
+ /** Verify the administrator independently. The contract reader only checks the credential shape. */
31
+ const adminRequestOf = <TInput>(
32
+ value: unknown, readInput: (input: unknown) => TInput,
33
+ ): IControlledTakeoverAdminRequest<TInput> => {
34
+ const request = readExactDataRecord(value, ['identity', 'input']);
35
+ const identity = request && readExactDataRecord(request.identity, ['jwt']);
36
+ if (!request || typeof identity?.jwt !== 'string' || identity.jwt.length === 0) {
37
+ throw new Error('Controlled takeover administrator request rejected.');
38
+ }
39
+ return { identity: { jwt: identity.jwt }, input: readInput(request.input) };
40
+ };
41
+
42
+ export const snapshotStartControlledTakeoverRequest = (value: unknown) =>
43
+ adminRequestOf(value, snapshotControlledTakeoverStartInput);
44
+ export const snapshotGetControlledTakeoverOperationRequest = (value: unknown) =>
45
+ adminRequestOf(value, snapshotControlledTakeoverGetInput);
46
+ export const snapshotGetControlledTakeoverOperationsRequest = (value: unknown) =>
47
+ adminRequestOf(value, snapshotControlledTakeoverListInput);
48
+ export const snapshotAbortControlledTakeoverRequest = (value: unknown) =>
49
+ adminRequestOf(value, snapshotControlledTakeoverAbortInput);
50
+ export const snapshotConfigureNupstWebhookEndpointRequest = (value: unknown) =>
51
+ adminRequestOf(value, snapshotNupstWebhookEndpointConfigureInput);
52
+ export const snapshotRotateNupstWebhookEndpointSecretRequest = (value: unknown) =>
53
+ adminRequestOf(value, snapshotNupstWebhookEndpointRotateInput);
54
+
55
+ /** Operator admission. Cloudly derives locations and the service plan. The answer reports the
56
+ * operation as stored after admission, including when answering a retry of the same start. */
57
+ export interface IReq_Admin_Cloudly_StartControlledTakeover extends plugins.typedrequestInterfaces.implementsTR<
58
+ plugins.typedrequestInterfaces.ITypedRequest, IReq_Admin_Cloudly_StartControlledTakeover
59
+ > {
60
+ method: 'startControlledTakeover';
61
+ request: IControlledTakeoverAdminRequest<IControlledTakeoverStartInput>;
62
+ response: IControlledTakeoverOperationResponse;
63
+ }
64
+
65
+ /** Read the recorded operation without advancing it. */
66
+ export interface IReq_Admin_Cloudly_GetControlledTakeoverOperation extends plugins.typedrequestInterfaces.implementsTR<
67
+ plugins.typedrequestInterfaces.ITypedRequest, IReq_Admin_Cloudly_GetControlledTakeoverOperation
68
+ > {
69
+ method: 'getControlledTakeoverOperation';
70
+ request: IControlledTakeoverAdminRequest<IControlledTakeoverGetInput>;
71
+ response: IControlledTakeoverOperationResponse;
72
+ }
73
+
74
+ /** Read one page by operation ID. No delegated administrator scope admits these requests. */
75
+ export interface IReq_Admin_Cloudly_GetControlledTakeoverOperations extends plugins.typedrequestInterfaces.implementsTR<
76
+ plugins.typedrequestInterfaces.ITypedRequest, IReq_Admin_Cloudly_GetControlledTakeoverOperations
77
+ > {
78
+ method: 'getControlledTakeoverOperations';
79
+ request: IControlledTakeoverAdminRequest<IControlledTakeoverListInput>;
80
+ response: IControlledTakeoverListResponse;
81
+ }
82
+
83
+ /** Cloudly checks the observed revision and the irreversible commit fence in the same transaction. */
84
+ export interface IReq_Admin_Cloudly_AbortControlledTakeover extends plugins.typedrequestInterfaces.implementsTR<
85
+ plugins.typedrequestInterfaces.ITypedRequest, IReq_Admin_Cloudly_AbortControlledTakeover
86
+ > {
87
+ method: 'abortControlledTakeover';
88
+ request: IControlledTakeoverAdminRequest<IControlledTakeoverAbortInput>;
89
+ response: TControlledTakeoverAbortResponse;
90
+ }
91
+
92
+ /** Configure the endpoint's site binding, enabled state and margin. Secret state is server-owned. */
93
+ export interface IReq_Admin_Cloudly_ConfigureNupstWebhookEndpoint extends plugins.typedrequestInterfaces.implementsTR<
94
+ plugins.typedrequestInterfaces.ITypedRequest, IReq_Admin_Cloudly_ConfigureNupstWebhookEndpoint
95
+ > {
96
+ method: 'configureNupstWebhookEndpoint';
97
+ request: IControlledTakeoverAdminRequest<INupstWebhookEndpointConfigureInput>;
98
+ response: INupstWebhookEndpointResponse;
99
+ }
100
+
101
+ /** Rotate against the observed secret version. Provisioning the sender happens outside this RPC. */
102
+ export interface IReq_Admin_Cloudly_RotateNupstWebhookEndpointSecret extends plugins.typedrequestInterfaces.implementsTR<
103
+ plugins.typedrequestInterfaces.ITypedRequest, IReq_Admin_Cloudly_RotateNupstWebhookEndpointSecret
104
+ > {
105
+ method: 'rotateNupstWebhookEndpointSecret';
106
+ request: IControlledTakeoverAdminRequest<INupstWebhookEndpointRotateInput>;
107
+ response: INupstWebhookEndpointResponse;
108
+ }
@@ -110,3 +110,4 @@ export * as gatewaycertificatestore from './gatewaycertificatestore.js';
110
110
  export * as dcstorage from './dcstorage.js';
111
111
  export * as preparedimages from './preparedimages.js';
112
112
  export * as corestorereplication from './corestorereplication.js';
113
+ export * as controlledtakeover from './controlledtakeover.js';