import * as plugins from './plugins.runtime.js'; import { canonicalizeStrictJson, deepFreezeValue, } from './private/canonicaljson.js'; export const cloudlyLegacyDeploymentSettlementLimits = Object.freeze({ maximumIdentifierLength: 200, maximumSourceDocuments: 2000, maximumOperations: 500, maximumPlanBytes: 512 * 1024, maximumSafeResultBytes: 16 * 1024, maximumReceiptBytes: 512 * 1024, maximumAuthorityBytes: 16 * 1024, maximumAuthenticatedArtifactBytes: 768 * 1024, maximumAuthorityLifetimeMs: 24 * 60 * 60 * 1000, maximumFailureReasons: 32, }); export const cloudlyLegacyDeploymentSettlementDomains = Object.freeze({ authorityAad: 'serve.zone/cloudly-legacy-deployment-settlement/authority-aad-v1\0', rehearsalBindingHmac: 'serve.zone/cloudly-legacy-deployment-settlement/rehearsal-binding-hmac-v1\0', planHmac: 'serve.zone/cloudly-legacy-deployment-settlement/plan-hmac-v1\0', productionRequestHmac: 'serve.zone/cloudly-legacy-deployment-settlement/production-request-hmac-v1\0', checkResultHmac: 'serve.zone/cloudly-legacy-deployment-settlement/check-result-hmac-v1\0', applyResultHmac: 'serve.zone/cloudly-legacy-deployment-settlement/apply-result-hmac-v1\0', stableOutcomeHmac: 'serve.zone/cloudly-legacy-deployment-settlement/stable-outcome-hmac-v1\0', scratchReceiptHmac: 'serve.zone/cloudly-legacy-deployment-settlement/scratch-receipt-hmac-v1\0', productionReceiptHmac: 'serve.zone/cloudly-legacy-deployment-settlement/production-receipt-hmac-v1\0', productionExecutionAuthorizationHmac: 'serve.zone/cloudly-legacy-deployment-settlement/production-execution-authorization-hmac-v1\0', productionReceiptV2Hmac: 'serve.zone/cloudly-legacy-deployment-settlement/production-receipt-hmac-v2\0', resolutionHmac: 'serve.zone/cloudly-legacy-deployment-settlement/resolution-recovery-attestation-hmac-v1\0', } as const); export type TCloudlyLegacyDeploymentSettlementCodecErrorCode = | 'INVALID_DATA' | 'INVALID_SCHEMA' | 'INVALID_VALUE' | 'LIMIT_EXCEEDED' | 'ORDERING_REQUIRED' | 'CROSS_FIELD_MISMATCH'; /** Safe error surface: code and schema path are finite and never contain values. */ export class CloudlyLegacyDeploymentSettlementCodecError extends Error { public readonly code: TCloudlyLegacyDeploymentSettlementCodecErrorCode; public readonly path: string; public constructor( codeArg: TCloudlyLegacyDeploymentSettlementCodecErrorCode, pathArg: string, ) { super(`${codeArg}:${pathArg}`); this.name = 'CloudlyLegacyDeploymentSettlementCodecError'; this.code = codeArg; this.path = pathArg; } } export type TCloudlyLegacyDeploymentSettlementClassification = | 'image-recorded-not-current' | 'image-recorded-current-failed' | 'rolling-out-current-failed' | 'rolling-out-superseded'; export interface ICloudlyLegacyDeploymentSettlementClassificationCountsV1 { 'image-recorded-not-current': number; 'image-recorded-current-failed': number; 'rolling-out-current-failed': number; 'rolling-out-superseded': number; } export interface ICloudlyLegacyDeploymentSettlementAuthorityReferenceV1 { operationId: string; authorityId: string; keyId: string; keyVersion: 1; authorityMetadataSha256: string; } interface ICloudlyLegacyDeploymentSettlementAuthorityMetadataBaseV1 { schemaVersion: 1; operationId: string; authorityId: string; keyId: string; keyVersion: 1; settlementId: string; issuedAt: number; expiresAt: number; maintenanceImageDigest: `sha256:${string}`; sourceImageDigest: `sha256:${string}`; targetImageDigest: `sha256:${string}`; targetVersion: string; targetManifestSha256: string; targetConfigSha256: string; backupId: string; backupSnapshotIdSha256: string; backupProofSha256: string; runId: string; rehearsalId: string; scratchServiceId: string; allocationId: string; allocationGeneration: number; allocationBindingSha256: string; allocationReceiptSha256: string; sourceDataSha256: string; restoredDataSha256: string; digestProofSha256: string; } export interface ICloudlyLegacyDeploymentSettlementAuthorityMetadataV1 extends ICloudlyLegacyDeploymentSettlementAuthorityMetadataBaseV1 { executionProtocol?: 'fenced-attempt-v1'; sourceAuthority?: ICloudlyLegacyDeploymentSettlementAuthorityReferenceV1; sourceAuthenticatedPlanSha256?: string; sourceRequestBundleSha256?: string; scratchReceiptSha256?: string; } export interface ICloudlyLegacyDeploymentSettlementLegacyAuthorityMetadataV1 extends ICloudlyLegacyDeploymentSettlementAuthorityMetadataBaseV1 { executionProtocol?: never; sourceAuthority?: never; sourceAuthenticatedPlanSha256?: never; sourceRequestBundleSha256?: never; scratchReceiptSha256?: never; } export interface ICloudlyLegacyDeploymentSettlementFencedSourceAuthorityMetadataV1 extends ICloudlyLegacyDeploymentSettlementAuthorityMetadataBaseV1 { executionProtocol: 'fenced-attempt-v1'; sourceAuthority?: never; sourceAuthenticatedPlanSha256?: never; sourceRequestBundleSha256?: never; scratchReceiptSha256?: never; } export interface ICloudlyLegacyDeploymentSettlementFencedProductionAuthorityMetadataV1 extends ICloudlyLegacyDeploymentSettlementAuthorityMetadataBaseV1 { executionProtocol: 'fenced-attempt-v1'; sourceAuthority: ICloudlyLegacyDeploymentSettlementAuthorityReferenceV1; sourceAuthenticatedPlanSha256: string; sourceRequestBundleSha256: string; scratchReceiptSha256: string; } export type TCloudlyLegacyDeploymentSettlementAuthorityMetadataV1 = | ICloudlyLegacyDeploymentSettlementLegacyAuthorityMetadataV1 | ICloudlyLegacyDeploymentSettlementFencedSourceAuthorityMetadataV1 | ICloudlyLegacyDeploymentSettlementFencedProductionAuthorityMetadataV1; /** Private plaintext HMAC key. Never persist, log, or place in summaries or receipts. */ export interface ICloudlyLegacyDeploymentSettlementHmacKeyPlaintextV1 { format: 'raw-32-byte-base64url'; value: string; } /** * Exact private-file handoff parsed by pinned maintenance containers. * Consumers own secure generation, storage, use, and destruction of the key. * Interfaces never generates, persists, or logs it; the private stdio verifier * transiently decodes it for HMAC verification and wipes the decoded bytes. */ export interface ICloudlyLegacyDeploymentSettlementAuthorityHandoffPlaintextV1 { schemaVersion: 1; kind: 'cloudly-legacy-deployment-settlement-authority-handoff-plaintext'; authorityMetadata: ICloudlyLegacyDeploymentSettlementAuthorityMetadataV1; authorityReference: ICloudlyLegacyDeploymentSettlementAuthorityReferenceV1; hmacKeyPlaintext: ICloudlyLegacyDeploymentSettlementHmacKeyPlaintextV1; } export interface ICloudlyLegacyDeploymentSettlementSourceCensusV1 { operations: number; services: number; images: number; releases: number; rolloutOperations: number; routeClaims: number; resourceClaims: number; } export interface ICloudlyLegacyDeploymentSettlementPlanEntryV1 { operationId: string; serviceId: string; sourceRevision: number; sourceState: 'image-recorded' | 'rolling-out'; classification: TCloudlyLegacyDeploymentSettlementClassification; finalRevision: number; sourceDocumentHmac: `hmac-sha256:${string}`; finalDocumentHmac: `hmac-sha256:${string}`; routeClaimsStabilized: number; routeClaimsRemoved: number; resourceClaimsRemoved: number; } export interface ICloudlyLegacyDeploymentSettlementPlanV1 { schemaVersion: 1; kind: 'cloudly-legacy-deployment-settlement-plan'; authority: ICloudlyLegacyDeploymentSettlementAuthorityReferenceV1; settlementId: string; effectiveAt: number; sourceStateHmac: `hmac-sha256:${string}`; finalStateHmac: `hmac-sha256:${string}`; sourceCensus: ICloudlyLegacyDeploymentSettlementSourceCensusV1; entries: ICloudlyLegacyDeploymentSettlementPlanEntryV1[]; classificationCounts: ICloudlyLegacyDeploymentSettlementClassificationCountsV1; operationCount: number; } export interface ICloudlyLegacyDeploymentSettlementProductionRequestV1 { schemaVersion: 1; kind: 'cloudly-legacy-deployment-settlement-production-request'; authority: ICloudlyLegacyDeploymentSettlementAuthorityReferenceV1; plan: ICloudlyLegacyDeploymentSettlementPlanV1; planSha256: string; rehearsalBinding: ICloudlyLegacyDeploymentSettlementRehearsalBindingV1; rehearsalBindingSha256: string; requestedAt: number; } export interface ICloudlyLegacyDeploymentSettlementMutationCountsV1 { operationCount: number; routeClaimsStabilized: number; routeClaimsRemoved: number; resourceClaimsRemoved: number; } export type TCloudlyLegacyDeploymentSettlementFailureReason = | 'AUTHORITY_INVALID' | 'AUTHORITY_EXPIRED' | 'REQUEST_MISMATCH' | 'PLAN_MISMATCH' | 'SOURCE_STATE_MISMATCH' | 'FINAL_STATE_MISMATCH' | 'TRANSACTIONS_UNSUPPORTED' | 'OPERATION_DRIFT' | 'CLAIM_DRIFT' | 'CLASSIFICATION_MISMATCH'; interface ICloudlyLegacyDeploymentSettlementSafeResultBaseV1 { schemaVersion: 1; requestSha256: string; planSha256: string; settlementId: string; sourceStateHmac: `hmac-sha256:${string}`; finalStateHmac: `hmac-sha256:${string}`; transactionSupported: boolean; counts: ICloudlyLegacyDeploymentSettlementMutationCountsV1; classificationCounts: ICloudlyLegacyDeploymentSettlementClassificationCountsV1; } export type TCloudlyLegacyDeploymentSettlementCheckResultV1 = | (ICloudlyLegacyDeploymentSettlementSafeResultBaseV1 & { kind: 'cloudly-legacy-deployment-settlement-check-result'; status: 'ready'; disposition: 'unapplied' | 'exact-replay' | 'no-op'; checkedAt: number; }) | (ICloudlyLegacyDeploymentSettlementSafeResultBaseV1 & { kind: 'cloudly-legacy-deployment-settlement-check-result'; status: 'blocked'; disposition: 'unapplied'; failureReasons: TCloudlyLegacyDeploymentSettlementFailureReason[]; checkedAt: number; }); export type TCloudlyLegacyDeploymentSettlementApplyResultV1 = | (ICloudlyLegacyDeploymentSettlementSafeResultBaseV1 & { kind: 'cloudly-legacy-deployment-settlement-apply-result'; status: 'completed'; disposition: 'applied' | 'exact-replay' | 'no-op'; completedAt: number; }) | (ICloudlyLegacyDeploymentSettlementSafeResultBaseV1 & { kind: 'cloudly-legacy-deployment-settlement-apply-result'; status: 'rejected'; disposition: 'unapplied'; failureReasons: TCloudlyLegacyDeploymentSettlementFailureReason[]; rejectedAt: number; }); export interface ICloudlyLegacyDeploymentSettlementRehearsalBindingV1 { schemaVersion: 1; kind: 'cloudly-legacy-deployment-settlement-rehearsal-binding'; settlementId: string; runId: string; rehearsalId: string; scratchServiceId: string; allocationId: string; allocationGeneration: number; allocationBindingSha256: string; allocationReceiptSha256: string; backupId: string; backupSnapshotIdSha256: string; backupProofSha256: string; sourceDataSha256: string; restoredDataSha256: string; digestProofSha256: string; targetImageDigest: `sha256:${string}`; targetVersion: string; targetManifestSha256: string; targetConfigSha256: string; } export interface ICloudlyLegacyDeploymentSettlementStableOutcomeV1 { schemaVersion: 1; kind: 'cloudly-legacy-deployment-settlement-stable-outcome'; settlementId: string; runId: string; rehearsalBindingSha256: string; effectiveAt: number; planSha256: string; sourceStateHmac: `hmac-sha256:${string}`; finalStateHmac: `hmac-sha256:${string}`; settlements: ICloudlyLegacyDeploymentSettlementStableOutcomeEntryV1[]; counts: ICloudlyLegacyDeploymentSettlementMutationCountsV1; classificationCounts: ICloudlyLegacyDeploymentSettlementClassificationCountsV1; } export interface ICloudlyLegacyDeploymentSettlementStableOutcomeEntryV1 { operationId: string; finalRevision: number; finalDocumentHmac: `hmac-sha256:${string}`; } export interface IAuthenticatedCloudlyLegacyDeploymentSettlementRehearsalBindingV1 { schemaVersion: 1; kind: 'authenticated-cloudly-legacy-deployment-settlement-rehearsal-binding'; authority: ICloudlyLegacyDeploymentSettlementAuthorityReferenceV1; payload: ICloudlyLegacyDeploymentSettlementRehearsalBindingV1; payloadSha256: string; mac: string; } export interface IAuthenticatedCloudlyLegacyDeploymentSettlementPlanV1 { schemaVersion: 1; kind: 'authenticated-cloudly-legacy-deployment-settlement-plan'; authority: ICloudlyLegacyDeploymentSettlementAuthorityReferenceV1; payload: ICloudlyLegacyDeploymentSettlementPlanV1; payloadSha256: string; mac: string; } export interface IAuthenticatedCloudlyLegacyDeploymentSettlementProductionRequestV1 { schemaVersion: 1; kind: 'authenticated-cloudly-legacy-deployment-settlement-production-request'; authority: ICloudlyLegacyDeploymentSettlementAuthorityReferenceV1; payload: ICloudlyLegacyDeploymentSettlementProductionRequestV1; payloadSha256: string; mac: string; } export interface IAuthenticatedCloudlyLegacyDeploymentSettlementCheckResultV1 { schemaVersion: 1; kind: 'authenticated-cloudly-legacy-deployment-settlement-check-result'; authority: ICloudlyLegacyDeploymentSettlementAuthorityReferenceV1; payload: TCloudlyLegacyDeploymentSettlementCheckResultV1; payloadSha256: string; mac: string; } export interface IAuthenticatedCloudlyLegacyDeploymentSettlementApplyResultV1 { schemaVersion: 1; kind: 'authenticated-cloudly-legacy-deployment-settlement-apply-result'; authority: ICloudlyLegacyDeploymentSettlementAuthorityReferenceV1; payload: TCloudlyLegacyDeploymentSettlementApplyResultV1; payloadSha256: string; mac: string; } export interface IAuthenticatedCloudlyLegacyDeploymentSettlementStableOutcomeV1 { schemaVersion: 1; kind: 'authenticated-cloudly-legacy-deployment-settlement-stable-outcome'; authority: ICloudlyLegacyDeploymentSettlementAuthorityReferenceV1; payload: ICloudlyLegacyDeploymentSettlementStableOutcomeV1; payloadSha256: string; mac: string; } export type TUnsignedAuthenticatedCloudlyLegacyDeploymentSettlementRehearsalBindingV1 = Omit; export type TUnsignedAuthenticatedCloudlyLegacyDeploymentSettlementPlanV1 = Omit; export type TUnsignedAuthenticatedCloudlyLegacyDeploymentSettlementProductionRequestV1 = Omit; export type TUnsignedAuthenticatedCloudlyLegacyDeploymentSettlementCheckResultV1 = Omit; export type TUnsignedAuthenticatedCloudlyLegacyDeploymentSettlementApplyResultV1 = Omit; export type TUnsignedAuthenticatedCloudlyLegacyDeploymentSettlementStableOutcomeV1 = Omit; export interface ICloudlyLegacyDeploymentSettlementHmacVerificationInputV1 { authority: ICloudlyLegacyDeploymentSettlementAuthorityReferenceV1; domain: typeof cloudlyLegacyDeploymentSettlementDomains[keyof typeof cloudlyLegacyDeploymentSettlementDomains]; hmacInput: Uint8Array; mac: string; } /** Consumer-owned verification keeps all HMAC key use outside Interfaces. */ export type TCloudlyLegacyDeploymentSettlementHmacVerifier = ( inputArg: ICloudlyLegacyDeploymentSettlementHmacVerificationInputV1, ) => boolean | Promise; export interface ICloudlyLegacyDeploymentSettlementScratchReceiptV1 { schemaVersion: 1; kind: 'cloudly-legacy-deployment-settlement-scratch-receipt'; authority: ICloudlyLegacyDeploymentSettlementAuthorityReferenceV1; requestSha256: string; stableOutcome: ICloudlyLegacyDeploymentSettlementStableOutcomeV1; stableOutcomeSha256: string; transactionCommitted: true; disposition: 'applied' | 'exact-replay' | 'no-op'; completedAt: number; payloadSha256: string; mac: string; } export interface ICloudlyLegacyDeploymentSettlementProductionReceiptV1 { schemaVersion: 1; kind: 'cloudly-legacy-deployment-settlement-production-receipt'; authority: ICloudlyLegacyDeploymentSettlementAuthorityReferenceV1; requestSha256: string; scratchReceipt: ICloudlyLegacyDeploymentSettlementScratchReceiptV1; scratchReceiptSha256: string; stableOutcome: ICloudlyLegacyDeploymentSettlementStableOutcomeV1; stableOutcomeSha256: string; transactionCommitted: true; disposition: 'applied' | 'exact-replay' | 'no-op'; completedAt: number; payloadSha256: string; mac: string; } export type TCloudlyLegacyDeploymentSettlementScratchReceiptPayloadV1 = Omit< ICloudlyLegacyDeploymentSettlementScratchReceiptV1, 'payloadSha256' | 'mac' >; export type TCloudlyLegacyDeploymentSettlementUnsignedScratchReceiptV1 = Omit< ICloudlyLegacyDeploymentSettlementScratchReceiptV1, 'mac' >; export type TCloudlyLegacyDeploymentSettlementProductionReceiptPayloadV1 = Omit< ICloudlyLegacyDeploymentSettlementProductionReceiptV1, 'payloadSha256' | 'mac' >; export type TCloudlyLegacyDeploymentSettlementUnsignedProductionReceiptV1 = Omit< ICloudlyLegacyDeploymentSettlementProductionReceiptV1, 'mac' >; const authorityCoreKeys = ['operationId', 'authorityId', 'keyId', 'keyVersion'] as const; const authorityReferenceKeys = [...authorityCoreKeys, 'authorityMetadataSha256'] as const; const authorityMetadataKeys = [ 'schemaVersion', ...authorityCoreKeys, 'settlementId', 'issuedAt', 'expiresAt', 'maintenanceImageDigest', 'sourceImageDigest', 'targetImageDigest', 'targetVersion', 'targetManifestSha256', 'targetConfigSha256', 'backupId', 'backupSnapshotIdSha256', 'backupProofSha256', 'runId', 'rehearsalId', 'scratchServiceId', 'allocationId', 'allocationGeneration', 'allocationBindingSha256', 'allocationReceiptSha256', 'sourceDataSha256', 'restoredDataSha256', 'digestProofSha256', ] as const; const authorityMetadataOptionalKeys = [ 'executionProtocol', 'sourceAuthority', 'sourceAuthenticatedPlanSha256', 'sourceRequestBundleSha256', 'scratchReceiptSha256', ] as const; const authorityMetadataCrossAuthorityKeys = [ 'schemaVersion', 'operationId', 'keyVersion', 'settlementId', 'maintenanceImageDigest', 'sourceImageDigest', 'targetImageDigest', 'targetVersion', 'targetManifestSha256', 'targetConfigSha256', 'backupId', 'backupSnapshotIdSha256', 'backupProofSha256', 'runId', 'rehearsalId', 'scratchServiceId', 'allocationId', 'allocationGeneration', 'allocationBindingSha256', 'allocationReceiptSha256', 'sourceDataSha256', 'restoredDataSha256', 'digestProofSha256', ] as const; const classificationKeys = [ 'image-recorded-not-current', 'image-recorded-current-failed', 'rolling-out-current-failed', 'rolling-out-superseded', ] as const; const censusKeys = [ 'operations', 'services', 'images', 'releases', 'rolloutOperations', 'routeClaims', 'resourceClaims', ] as const; const mutationCountKeys = [ 'operationCount', 'routeClaimsStabilized', 'routeClaimsRemoved', 'resourceClaimsRemoved', ] as const; const planEntryKeys = [ 'operationId', 'serviceId', 'sourceRevision', 'sourceState', 'classification', 'finalRevision', 'sourceDocumentHmac', 'finalDocumentHmac', 'routeClaimsStabilized', 'routeClaimsRemoved', 'resourceClaimsRemoved', ] as const; const failureReasons = new Set([ 'AUTHORITY_INVALID', 'AUTHORITY_EXPIRED', 'REQUEST_MISMATCH', 'PLAN_MISMATCH', 'SOURCE_STATE_MISMATCH', 'FINAL_STATE_MISMATCH', 'TRANSACTIONS_UNSUPPORTED', 'OPERATION_DRIFT', 'CLAIM_DRIFT', 'CLASSIFICATION_MISMATCH', ]); const identifierPattern = /^[A-Za-z0-9][A-Za-z0-9:._@-]{0,199}$/; const sha256Pattern = /^[a-f0-9]{64}$/; const ociDigestPattern = /^sha256:[a-f0-9]{64}$/; const stateHmacPattern = /^hmac-sha256:[a-f0-9]{64}$/; const macPattern = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/; const raw32ByteBase64UrlPattern = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/; const fail = ( codeArg: TCloudlyLegacyDeploymentSettlementCodecErrorCode, pathArg: string, ): never => { throw new CloudlyLegacyDeploymentSettlementCodecError(codeArg, pathArg); }; const readRecord = (valueArg: unknown, pathArg: string): Record => { if (!valueArg || typeof valueArg !== 'object' || Array.isArray(valueArg)) { return fail('INVALID_DATA', pathArg); } const prototype = Object.getPrototypeOf(valueArg); if (prototype !== Object.prototype && prototype !== null) { return fail('INVALID_DATA', pathArg); } const record = valueArg as Record; for (const key of Reflect.ownKeys(record)) { if (typeof key !== 'string') return fail('INVALID_DATA', pathArg); const descriptor = Object.getOwnPropertyDescriptor(record, key); if (!descriptor || !descriptor.enumerable || !Object.hasOwn(descriptor, 'value')) { return fail('INVALID_DATA', pathArg); } } return record; }; const readArray = ( valueArg: unknown, pathArg: string, maximumLengthArg: number, minimumLengthArg = 0, ): unknown[] => { if (!Array.isArray(valueArg) || Object.getPrototypeOf(valueArg) !== Array.prototype) { return fail('INVALID_DATA', pathArg); } if (valueArg.length < minimumLengthArg || valueArg.length > maximumLengthArg) { return fail('LIMIT_EXCEEDED', pathArg); } for (let index = 0; index < valueArg.length; index++) { if (!Object.hasOwn(valueArg, index)) return fail('INVALID_DATA', `${pathArg}[${index}]`); const descriptor = Object.getOwnPropertyDescriptor(valueArg, String(index)); if (!descriptor || !descriptor.enumerable || !Object.hasOwn(descriptor, 'value')) { return fail('INVALID_DATA', `${pathArg}[${index}]`); } } for (const key of Reflect.ownKeys(valueArg)) { if (key === 'length') continue; if (typeof key !== 'string' || !/^(?:0|[1-9][0-9]*)$/.test(key) || Number(key) >= valueArg.length) { return fail('INVALID_DATA', pathArg); } } return valueArg; }; const assertExactKeys = ( valueArg: Record, keysArg: readonly string[], pathArg: string, ): void => { const actual = Object.keys(valueArg).sort((leftArg, rightArg) => ( leftArg < rightArg ? -1 : leftArg > rightArg ? 1 : 0 )); const expected = [...keysArg].sort((leftArg, rightArg) => ( leftArg < rightArg ? -1 : leftArg > rightArg ? 1 : 0 )); if (actual.length !== expected.length || actual.some((keyArg, indexArg) => keyArg !== expected[indexArg])) { fail('INVALID_SCHEMA', pathArg); } }; const readIdentifier = (valueArg: unknown, pathArg: string): string => { if (typeof valueArg !== 'string' || !identifierPattern.test(valueArg)) { return fail('INVALID_VALUE', pathArg); } return valueArg; }; const readSha256 = (valueArg: unknown, pathArg: string): string => { if (typeof valueArg !== 'string' || !sha256Pattern.test(valueArg)) { return fail('INVALID_VALUE', pathArg); } return valueArg; }; const readOciDigest = (valueArg: unknown, pathArg: string): `sha256:${string}` => { if (typeof valueArg !== 'string' || !ociDigestPattern.test(valueArg)) { return fail('INVALID_VALUE', pathArg); } return valueArg as `sha256:${string}`; }; const readStateHmac = (valueArg: unknown, pathArg: string): `hmac-sha256:${string}` => { if (typeof valueArg !== 'string' || !stateHmacPattern.test(valueArg)) { return fail('INVALID_VALUE', pathArg); } return valueArg as `hmac-sha256:${string}`; }; const readMac = (valueArg: unknown, pathArg: string): string => { if (typeof valueArg !== 'string' || !macPattern.test(valueArg)) { return fail('INVALID_VALUE', pathArg); } const bytes = Buffer.from(valueArg, 'base64url'); if (bytes.byteLength !== 32 || bytes.toString('base64url') !== valueArg) { return fail('INVALID_VALUE', pathArg); } return valueArg; }; const readInteger = ( valueArg: unknown, pathArg: string, minimumArg = 0, maximumArg = Number.MAX_SAFE_INTEGER, ): number => { if (typeof valueArg !== 'number' || !Number.isSafeInteger(valueArg) || Object.is(valueArg, -0) || valueArg < minimumArg || valueArg > maximumArg) { return fail('INVALID_VALUE', pathArg); } return valueArg; }; const readBoolean = (valueArg: unknown, pathArg: string): boolean => { if (typeof valueArg !== 'boolean') return fail('INVALID_VALUE', pathArg); return valueArg; }; const readLiteral = ( valueArg: unknown, literalsArg: readonly TLiteral[], pathArg: string, ): TLiteral => { if (typeof valueArg !== 'string' || !literalsArg.includes(valueArg as TLiteral)) { return fail('INVALID_VALUE', pathArg); } return valueArg as TLiteral; }; const canonicalize = (valueArg: unknown, pathArg: string): string => ( canonicalizeStrictJson( valueArg, () => fail('INVALID_DATA', pathArg), pathArg, ) ); const finalize = ( valueArg: T, maximumBytesArg: number, pathArg: string, ): Readonly => { const json = canonicalize(valueArg, pathArg); if (Buffer.byteLength(json, 'utf8') > maximumBytesArg) { return fail('LIMIT_EXCEEDED', pathArg); } return deepFreezeValue(valueArg); }; const encodeNormalized = (valueArg: unknown, pathArg: string): Uint8Array => ( Buffer.from(canonicalize(valueArg, pathArg), 'utf8') ); const frame = (domainArg: string, payloadArg: Uint8Array): Uint8Array => { const domain = Buffer.from(domainArg, 'utf8'); const output = new Uint8Array(domain.byteLength + payloadArg.byteLength); output.set(domain, 0); output.set(payloadArg, domain.byteLength); return output; }; const digestBytes = (valueArg: Uint8Array): string => ( plugins.crypto.createHash('sha256').update(new Uint8Array(valueArg)).digest('hex') ); const normalizeAuthorityReferenceInternal = ( valueArg: unknown, pathArg: string, ): ICloudlyLegacyDeploymentSettlementAuthorityReferenceV1 => { const value = readRecord(valueArg, pathArg); assertExactKeys(value, authorityReferenceKeys, pathArg); if (value.keyVersion !== 1) fail('INVALID_VALUE', `${pathArg}.keyVersion`); return { operationId: readIdentifier(value.operationId, `${pathArg}.operationId`), authorityId: readIdentifier(value.authorityId, `${pathArg}.authorityId`), keyId: readIdentifier(value.keyId, `${pathArg}.keyId`), keyVersion: 1, authorityMetadataSha256: readSha256( value.authorityMetadataSha256, `${pathArg}.authorityMetadataSha256`, ), }; }; export const normalizeCloudlyLegacyDeploymentSettlementAuthorityReference = ( valueArg: unknown, ): Readonly => finalize( normalizeAuthorityReferenceInternal(valueArg, 'authorityReference'), cloudlyLegacyDeploymentSettlementLimits.maximumAuthorityBytes, 'authorityReference', ); const normalizeAuthorityMetadataInternal = ( valueArg: unknown, pathArg: string, ): TCloudlyLegacyDeploymentSettlementAuthorityMetadataV1 => { const value = readRecord(valueArg, pathArg); const optionalKeys = authorityMetadataOptionalKeys.filter((keyArg) => Object.hasOwn(value, keyArg)); assertExactKeys(value, [...authorityMetadataKeys, ...optionalKeys], pathArg); if (value.schemaVersion !== 1 || value.keyVersion !== 1) { fail('INVALID_VALUE', `${pathArg}.schemaVersion`); } const issuedAt = readInteger(value.issuedAt, `${pathArg}.issuedAt`, 1); const expiresAt = readInteger(value.expiresAt, `${pathArg}.expiresAt`, 1); if (expiresAt <= issuedAt || expiresAt - issuedAt > cloudlyLegacyDeploymentSettlementLimits.maximumAuthorityLifetimeMs) { fail('CROSS_FIELD_MISMATCH', `${pathArg}.expiresAt`); } const sourceDataSha256 = readSha256( value.sourceDataSha256, `${pathArg}.sourceDataSha256`, ); const restoredDataSha256 = readSha256( value.restoredDataSha256, `${pathArg}.restoredDataSha256`, ); if (sourceDataSha256 !== restoredDataSha256) { fail('CROSS_FIELD_MISMATCH', `${pathArg}.restoredDataSha256`); } const predecessorKeys = authorityMetadataOptionalKeys.filter((keyArg) => ( keyArg !== 'executionProtocol' )); const hasExecutionProtocol = Object.hasOwn(value, 'executionProtocol'); const predecessorKeyCount = predecessorKeys.filter((keyArg) => Object.hasOwn(value, keyArg)).length; if (hasExecutionProtocol && value.executionProtocol !== 'fenced-attempt-v1') { fail('INVALID_VALUE', `${pathArg}.executionProtocol`); } if (predecessorKeyCount !== 0 && predecessorKeyCount !== predecessorKeys.length) { fail('INVALID_SCHEMA', `${pathArg}.sourceAuthority`); } if (predecessorKeyCount > 0 && !hasExecutionProtocol) { fail('CROSS_FIELD_MISMATCH', `${pathArg}.executionProtocol`); } const operationId = readIdentifier(value.operationId, `${pathArg}.operationId`); const authorityId = readIdentifier(value.authorityId, `${pathArg}.authorityId`); const keyId = readIdentifier(value.keyId, `${pathArg}.keyId`); const sourceAuthority = predecessorKeyCount === 0 ? undefined : normalizeAuthorityReferenceInternal(value.sourceAuthority, `${pathArg}.sourceAuthority`); if (sourceAuthority && (sourceAuthority.operationId !== operationId || sourceAuthority.authorityId === authorityId || sourceAuthority.keyId === keyId)) { fail('CROSS_FIELD_MISMATCH', `${pathArg}.sourceAuthority`); } const common: ICloudlyLegacyDeploymentSettlementAuthorityMetadataBaseV1 = { schemaVersion: 1, operationId, authorityId, keyId, keyVersion: 1, settlementId: readIdentifier(value.settlementId, `${pathArg}.settlementId`), issuedAt, expiresAt, maintenanceImageDigest: readOciDigest( value.maintenanceImageDigest, `${pathArg}.maintenanceImageDigest`, ), sourceImageDigest: readOciDigest(value.sourceImageDigest, `${pathArg}.sourceImageDigest`), targetImageDigest: readOciDigest(value.targetImageDigest, `${pathArg}.targetImageDigest`), targetVersion: readIdentifier(value.targetVersion, `${pathArg}.targetVersion`), targetManifestSha256: readSha256( value.targetManifestSha256, `${pathArg}.targetManifestSha256`, ), targetConfigSha256: readSha256(value.targetConfigSha256, `${pathArg}.targetConfigSha256`), backupId: readIdentifier(value.backupId, `${pathArg}.backupId`), backupSnapshotIdSha256: readSha256( value.backupSnapshotIdSha256, `${pathArg}.backupSnapshotIdSha256`, ), backupProofSha256: readSha256(value.backupProofSha256, `${pathArg}.backupProofSha256`), runId: readIdentifier(value.runId, `${pathArg}.runId`), rehearsalId: readIdentifier(value.rehearsalId, `${pathArg}.rehearsalId`), scratchServiceId: readIdentifier(value.scratchServiceId, `${pathArg}.scratchServiceId`), allocationId: readIdentifier(value.allocationId, `${pathArg}.allocationId`), allocationGeneration: readInteger( value.allocationGeneration, `${pathArg}.allocationGeneration`, 1, ), allocationBindingSha256: readSha256( value.allocationBindingSha256, `${pathArg}.allocationBindingSha256`, ), allocationReceiptSha256: readSha256( value.allocationReceiptSha256, `${pathArg}.allocationReceiptSha256`, ), sourceDataSha256, restoredDataSha256, digestProofSha256: readSha256(value.digestProofSha256, `${pathArg}.digestProofSha256`), }; if (!hasExecutionProtocol) { return common as ICloudlyLegacyDeploymentSettlementLegacyAuthorityMetadataV1; } if (!sourceAuthority) { return { ...common, executionProtocol: 'fenced-attempt-v1', } as ICloudlyLegacyDeploymentSettlementFencedSourceAuthorityMetadataV1; } return { ...common, executionProtocol: 'fenced-attempt-v1', sourceAuthority, sourceAuthenticatedPlanSha256: readSha256( value.sourceAuthenticatedPlanSha256, `${pathArg}.sourceAuthenticatedPlanSha256`, ), sourceRequestBundleSha256: readSha256( value.sourceRequestBundleSha256, `${pathArg}.sourceRequestBundleSha256`, ), scratchReceiptSha256: readSha256( value.scratchReceiptSha256, `${pathArg}.scratchReceiptSha256`, ), } as ICloudlyLegacyDeploymentSettlementFencedProductionAuthorityMetadataV1; }; export const normalizeCloudlyLegacyDeploymentSettlementAuthorityMetadata = ( valueArg: unknown, ): Readonly => finalize( normalizeAuthorityMetadataInternal(valueArg, 'authorityMetadata'), cloudlyLegacyDeploymentSettlementLimits.maximumAuthorityBytes, 'authorityMetadata', ); export const encodeCloudlyLegacyDeploymentSettlementAuthorityMetadata = ( valueArg: unknown, ): Uint8Array => encodeNormalized( normalizeCloudlyLegacyDeploymentSettlementAuthorityMetadata(valueArg), 'authorityMetadata', ); export const encodeCloudlyLegacyDeploymentSettlementAuthorityMetadataAad = ( valueArg: unknown, ): Uint8Array => frame( cloudlyLegacyDeploymentSettlementDomains.authorityAad, encodeCloudlyLegacyDeploymentSettlementAuthorityMetadata(valueArg), ); export const digestCloudlyLegacyDeploymentSettlementAuthorityMetadata = ( valueArg: unknown, ): string => digestBytes(encodeCloudlyLegacyDeploymentSettlementAuthorityMetadata(valueArg)); export const createCloudlyLegacyDeploymentSettlementAuthorityReference = ( metadataArg: unknown, ): Readonly => { const metadata = normalizeCloudlyLegacyDeploymentSettlementAuthorityMetadata(metadataArg); return finalize({ operationId: metadata.operationId, authorityId: metadata.authorityId, keyId: metadata.keyId, keyVersion: metadata.keyVersion, authorityMetadataSha256: digestCloudlyLegacyDeploymentSettlementAuthorityMetadata(metadata), }, cloudlyLegacyDeploymentSettlementLimits.maximumAuthorityBytes, 'authorityReference'); }; export const normalizeCloudlyLegacyDeploymentSettlementAuthorityReferenceForMetadata = ( referenceArg: unknown, metadataArg: unknown, ): Readonly => { const reference = normalizeCloudlyLegacyDeploymentSettlementAuthorityReference(referenceArg); const expected = createCloudlyLegacyDeploymentSettlementAuthorityReference(metadataArg); if (canonicalize(reference, 'authorityReference') !== canonicalize(expected, 'authorityReference.expected')) { fail('CROSS_FIELD_MISMATCH', 'authorityReference'); } return reference; }; const normalizeFencedSourceAuthorityMetadata = ( metadataArg: unknown, pathArg: string, ): Readonly => { const metadata = normalizeCloudlyLegacyDeploymentSettlementAuthorityMetadata(metadataArg); if (metadata.executionProtocol !== 'fenced-attempt-v1' || Object.hasOwn(metadata, 'sourceAuthority')) { fail('CROSS_FIELD_MISMATCH', pathArg); } return metadata as Readonly< ICloudlyLegacyDeploymentSettlementFencedSourceAuthorityMetadataV1 >; }; const normalizeProductionAuthorityMetadataPair = ( productionMetadataArg: unknown, sourceMetadataArg: unknown, ): { productionMetadata: Readonly< ICloudlyLegacyDeploymentSettlementFencedProductionAuthorityMetadataV1 >; sourceMetadata: Readonly; } => { const productionMetadata = normalizeCloudlyLegacyDeploymentSettlementAuthorityMetadata( productionMetadataArg, ); const sourceMetadata = normalizeFencedSourceAuthorityMetadata( sourceMetadataArg, 'sourceAuthorityMetadata', ); if (productionMetadata.executionProtocol !== 'fenced-attempt-v1' || !Object.hasOwn(productionMetadata, 'sourceAuthority')) { fail('CROSS_FIELD_MISMATCH', 'productionAuthorityMetadata'); } const fencedSourceMetadata = sourceMetadata; const fencedProductionMetadata = productionMetadata as Readonly< ICloudlyLegacyDeploymentSettlementFencedProductionAuthorityMetadataV1 >; const sourceAuthority = createCloudlyLegacyDeploymentSettlementAuthorityReference( fencedSourceMetadata, ); const productionAuthority = createCloudlyLegacyDeploymentSettlementAuthorityReference( fencedProductionMetadata, ); const sourceContext = Object.fromEntries(authorityMetadataCrossAuthorityKeys.map((keyArg) => [ keyArg, fencedSourceMetadata[keyArg], ])); const productionContext = Object.fromEntries(authorityMetadataCrossAuthorityKeys.map((keyArg) => [ keyArg, fencedProductionMetadata[keyArg], ])); if (canonicalize(fencedProductionMetadata.sourceAuthority, 'productionMetadata.sourceAuthority') !== canonicalize(sourceAuthority, 'sourceMetadata.authority') || canonicalize(productionAuthority, 'productionMetadata.authority') === canonicalize(sourceAuthority, 'sourceMetadata.authority') || fencedProductionMetadata.authorityId === fencedSourceMetadata.authorityId || fencedProductionMetadata.keyId === fencedSourceMetadata.keyId || canonicalize(productionContext, 'productionMetadata.context') !== canonicalize(sourceContext, 'sourceMetadata.context')) { fail('CROSS_FIELD_MISMATCH', 'productionAuthorityMetadata.sourceAuthority'); } return { productionMetadata: fencedProductionMetadata, sourceMetadata: fencedSourceMetadata, }; }; export const normalizeCloudlyLegacyDeploymentSettlementProductionAuthorityMetadataForSourceAuthority = ( productionMetadataArg: unknown, sourceMetadataArg: unknown, ): Readonly => ( normalizeProductionAuthorityMetadataPair(productionMetadataArg, sourceMetadataArg).productionMetadata ); export const normalizeCloudlyLegacyDeploymentSettlementAuthorityHandoffPlaintext = ( valueArg: unknown, ): Readonly => { const value = readRecord(valueArg, 'authorityHandoffPlaintext'); assertExactKeys(value, [ 'schemaVersion', 'kind', 'authorityMetadata', 'authorityReference', 'hmacKeyPlaintext', ], 'authorityHandoffPlaintext'); if (value.schemaVersion !== 1 || value.kind !== 'cloudly-legacy-deployment-settlement-authority-handoff-plaintext') { fail('INVALID_VALUE', 'authorityHandoffPlaintext.kind'); } const authorityMetadata = normalizeAuthorityMetadataInternal( value.authorityMetadata, 'authorityHandoffPlaintext.authorityMetadata', ); const authorityReference = normalizeCloudlyLegacyDeploymentSettlementAuthorityReferenceForMetadata( value.authorityReference, authorityMetadata, ); const key = readRecord( value.hmacKeyPlaintext, 'authorityHandoffPlaintext.hmacKeyPlaintext', ); assertExactKeys( key, ['format', 'value'], 'authorityHandoffPlaintext.hmacKeyPlaintext', ); const keyValue = typeof key.value === 'string' ? key.value : fail('INVALID_VALUE', 'authorityHandoffPlaintext.hmacKeyPlaintext.value'); if (key.format !== 'raw-32-byte-base64url' || !raw32ByteBase64UrlPattern.test(keyValue)) { fail('INVALID_VALUE', 'authorityHandoffPlaintext.hmacKeyPlaintext'); } const keyBytes = Buffer.from(keyValue, 'base64url'); try { if (keyBytes.byteLength !== 32 || keyBytes.toString('base64url') !== keyValue) { fail('INVALID_VALUE', 'authorityHandoffPlaintext.hmacKeyPlaintext.value'); } } finally { keyBytes.fill(0); } return finalize({ schemaVersion: 1, kind: 'cloudly-legacy-deployment-settlement-authority-handoff-plaintext', authorityMetadata, authorityReference, hmacKeyPlaintext: { format: 'raw-32-byte-base64url', value: keyValue }, }, cloudlyLegacyDeploymentSettlementLimits.maximumAuthorityBytes, 'authorityHandoffPlaintext'); }; export const encodeCloudlyLegacyDeploymentSettlementAuthorityHandoffPlaintext = ( valueArg: unknown, ): Uint8Array => encodeNormalized( normalizeCloudlyLegacyDeploymentSettlementAuthorityHandoffPlaintext(valueArg), 'authorityHandoffPlaintext', ); /** * Private in-process stdio handoff verification only. Do not persist or log the * handoff or returned verifier; discard both as soon as the stdio exchange ends. */ export const createCloudlyLegacyDeploymentSettlementStdioHandoffHmacVerifier = ( handoffArg: unknown, ): TCloudlyLegacyDeploymentSettlementHmacVerifier => { const handoff = normalizeCloudlyLegacyDeploymentSettlementAuthorityHandoffPlaintext( handoffArg, ); const authorityCanonical = canonicalize( handoff.authorityReference, 'stdioHandoffHmacVerifier.authority', ); const keyValue = handoff.hmacKeyPlaintext.value; return (inputArg): boolean => { let keyBytes: Buffer | undefined; let suppliedMacBytes: Buffer | undefined; let expectedMacBytes: Buffer | undefined; try { if (!(inputArg.hmacInput instanceof Uint8Array) || canonicalize(inputArg.authority, 'stdioHandoffHmacVerifier.input.authority') !== authorityCanonical || !macPattern.test(inputArg.mac)) { return false; } const domainBytes = Buffer.from(inputArg.domain, 'utf8'); const hmacInputBytes = Buffer.from(inputArg.hmacInput); if (hmacInputBytes.byteLength < domainBytes.byteLength || !hmacInputBytes.subarray(0, domainBytes.byteLength).equals(domainBytes)) { return false; } keyBytes = Buffer.from(keyValue, 'base64url'); suppliedMacBytes = Buffer.from(inputArg.mac, 'base64url'); if (keyBytes.byteLength !== 32 || keyBytes.toString('base64url') !== keyValue || suppliedMacBytes.byteLength !== 32 || suppliedMacBytes.toString('base64url') !== inputArg.mac) { return false; } expectedMacBytes = plugins.crypto .createHmac('sha256', keyBytes) .update(hmacInputBytes) .digest(); return plugins.crypto.timingSafeEqual(expectedMacBytes, suppliedMacBytes); } catch { return false; } finally { keyBytes?.fill(0); suppliedMacBytes?.fill(0); expectedMacBytes?.fill(0); } }; }; const normalizeClassificationCounts = ( valueArg: unknown, pathArg: string, ): ICloudlyLegacyDeploymentSettlementClassificationCountsV1 => { const value = readRecord(valueArg, pathArg); assertExactKeys(value, classificationKeys, pathArg); return { 'image-recorded-not-current': readInteger( value['image-recorded-not-current'], `${pathArg}.image-recorded-not-current`, 0, cloudlyLegacyDeploymentSettlementLimits.maximumOperations, ), 'image-recorded-current-failed': readInteger( value['image-recorded-current-failed'], `${pathArg}.image-recorded-current-failed`, 0, cloudlyLegacyDeploymentSettlementLimits.maximumOperations, ), 'rolling-out-current-failed': readInteger( value['rolling-out-current-failed'], `${pathArg}.rolling-out-current-failed`, 0, cloudlyLegacyDeploymentSettlementLimits.maximumOperations, ), 'rolling-out-superseded': readInteger( value['rolling-out-superseded'], `${pathArg}.rolling-out-superseded`, 0, cloudlyLegacyDeploymentSettlementLimits.maximumOperations, ), }; }; const sumClassificationCounts = ( valueArg: ICloudlyLegacyDeploymentSettlementClassificationCountsV1, ): number => classificationKeys.reduce((sumArg, keyArg) => sumArg + valueArg[keyArg], 0); const normalizeSourceCensus = ( valueArg: unknown, pathArg: string, ): ICloudlyLegacyDeploymentSettlementSourceCensusV1 => { const value = readRecord(valueArg, pathArg); assertExactKeys(value, censusKeys, pathArg); const output = Object.fromEntries(censusKeys.map((keyArg) => [ keyArg, readInteger( value[keyArg], `${pathArg}.${keyArg}`, 0, cloudlyLegacyDeploymentSettlementLimits.maximumSourceDocuments, ), ])) as unknown as ICloudlyLegacyDeploymentSettlementSourceCensusV1; if (censusKeys.reduce((sumArg, keyArg) => sumArg + output[keyArg], 0) > cloudlyLegacyDeploymentSettlementLimits.maximumSourceDocuments) { fail('LIMIT_EXCEEDED', pathArg); } return output; }; const normalizeMutationCounts = ( valueArg: unknown, pathArg: string, ): ICloudlyLegacyDeploymentSettlementMutationCountsV1 => { const value = readRecord(valueArg, pathArg); assertExactKeys(value, mutationCountKeys, pathArg); return { operationCount: readInteger( value.operationCount, `${pathArg}.operationCount`, 0, cloudlyLegacyDeploymentSettlementLimits.maximumOperations, ), routeClaimsStabilized: readInteger(value.routeClaimsStabilized, `${pathArg}.routeClaimsStabilized`), routeClaimsRemoved: readInteger(value.routeClaimsRemoved, `${pathArg}.routeClaimsRemoved`), resourceClaimsRemoved: readInteger(value.resourceClaimsRemoved, `${pathArg}.resourceClaimsRemoved`), }; }; const assertCountsMatchClassifications = ( countsArg: ICloudlyLegacyDeploymentSettlementMutationCountsV1, classificationsArg: ICloudlyLegacyDeploymentSettlementClassificationCountsV1, pathArg: string, ): void => { if (countsArg.operationCount !== sumClassificationCounts(classificationsArg)) { fail('CROSS_FIELD_MISMATCH', pathArg); } }; const normalizePlanEntry = ( valueArg: unknown, pathArg: string, ): ICloudlyLegacyDeploymentSettlementPlanEntryV1 => { const value = readRecord(valueArg, pathArg); assertExactKeys(value, planEntryKeys, pathArg); const sourceRevision = readInteger(value.sourceRevision, `${pathArg}.sourceRevision`, 0); const finalRevision = readInteger(value.finalRevision, `${pathArg}.finalRevision`, 0); if (finalRevision !== sourceRevision + 3 || !Number.isSafeInteger(sourceRevision + 3)) { fail('CROSS_FIELD_MISMATCH', `${pathArg}.finalRevision`); } const sourceState = readLiteral( value.sourceState, ['image-recorded', 'rolling-out'], `${pathArg}.sourceState`, ); const classification = readLiteral( value.classification, classificationKeys, `${pathArg}.classification`, ); if ((classification.startsWith('image-recorded-') && sourceState !== 'image-recorded') || (classification.startsWith('rolling-out-') && sourceState !== 'rolling-out')) { fail('CROSS_FIELD_MISMATCH', `${pathArg}.classification`); } return { operationId: readIdentifier(value.operationId, `${pathArg}.operationId`), serviceId: readIdentifier(value.serviceId, `${pathArg}.serviceId`), sourceRevision, sourceState, classification, finalRevision, sourceDocumentHmac: readStateHmac(value.sourceDocumentHmac, `${pathArg}.sourceDocumentHmac`), finalDocumentHmac: readStateHmac(value.finalDocumentHmac, `${pathArg}.finalDocumentHmac`), routeClaimsStabilized: readInteger(value.routeClaimsStabilized, `${pathArg}.routeClaimsStabilized`), routeClaimsRemoved: readInteger(value.routeClaimsRemoved, `${pathArg}.routeClaimsRemoved`), resourceClaimsRemoved: readInteger(value.resourceClaimsRemoved, `${pathArg}.resourceClaimsRemoved`), }; }; export const normalizeCloudlyLegacyDeploymentSettlementPlan = ( valueArg: unknown, ): Readonly => { const value = readRecord(valueArg, 'plan'); assertExactKeys(value, [ 'schemaVersion', 'kind', 'authority', 'settlementId', 'effectiveAt', 'sourceStateHmac', 'finalStateHmac', 'sourceCensus', 'entries', 'classificationCounts', 'operationCount', ], 'plan'); if (value.schemaVersion !== 1 || value.kind !== 'cloudly-legacy-deployment-settlement-plan') { fail('INVALID_VALUE', 'plan.kind'); } const entries = readArray( value.entries, 'plan.entries', cloudlyLegacyDeploymentSettlementLimits.maximumOperations, ).map((entryArg, indexArg) => normalizePlanEntry(entryArg, `plan.entries[${indexArg}]`)); for (let index = 1; index < entries.length; index++) { if (entries[index - 1].operationId >= entries[index].operationId) { fail('ORDERING_REQUIRED', `plan.entries[${index}].operationId`); } } const classificationCounts = normalizeClassificationCounts( value.classificationCounts, 'plan.classificationCounts', ); const operationCount = readInteger( value.operationCount, 'plan.operationCount', 0, cloudlyLegacyDeploymentSettlementLimits.maximumOperations, ); if (operationCount !== entries.length || operationCount !== sumClassificationCounts(classificationCounts)) { fail('CROSS_FIELD_MISMATCH', 'plan.operationCount'); } const actualCounts = Object.fromEntries(classificationKeys.map((keyArg) => [ keyArg, entries.filter((entryArg) => entryArg.classification === keyArg).length, ])); if (classificationKeys.some((keyArg) => actualCounts[keyArg] !== classificationCounts[keyArg])) { fail('CROSS_FIELD_MISMATCH', 'plan.classificationCounts'); } return finalize({ schemaVersion: 1, kind: 'cloudly-legacy-deployment-settlement-plan', authority: normalizeAuthorityReferenceInternal(value.authority, 'plan.authority'), settlementId: readIdentifier(value.settlementId, 'plan.settlementId'), effectiveAt: readInteger(value.effectiveAt, 'plan.effectiveAt', 1), sourceStateHmac: readStateHmac(value.sourceStateHmac, 'plan.sourceStateHmac'), finalStateHmac: readStateHmac(value.finalStateHmac, 'plan.finalStateHmac'), sourceCensus: normalizeSourceCensus(value.sourceCensus, 'plan.sourceCensus'), entries, classificationCounts, operationCount, }, cloudlyLegacyDeploymentSettlementLimits.maximumPlanBytes, 'plan'); }; export const encodeCloudlyLegacyDeploymentSettlementPlan = ( valueArg: unknown, ): Uint8Array => encodeNormalized(normalizeCloudlyLegacyDeploymentSettlementPlan(valueArg), 'plan'); export const encodeCloudlyLegacyDeploymentSettlementPlanHmacInput = ( valueArg: unknown, ): Uint8Array => frame( cloudlyLegacyDeploymentSettlementDomains.planHmac, encodeNormalized( normalizeUnsignedAuthenticatedPlanInternal(valueArg, 'unsignedAuthenticatedPlan'), 'unsignedAuthenticatedPlan', ), ); export const digestCloudlyLegacyDeploymentSettlementPlan = ( valueArg: unknown, ): string => digestBytes(encodeCloudlyLegacyDeploymentSettlementPlan(valueArg)); const normalizeFailureReasons = ( valueArg: unknown, pathArg: string, ): TCloudlyLegacyDeploymentSettlementFailureReason[] => { const values = readArray( valueArg, pathArg, cloudlyLegacyDeploymentSettlementLimits.maximumFailureReasons, 1, ); const output = values.map((entryArg, indexArg) => { if (typeof entryArg !== 'string' || !failureReasons.has(entryArg as TCloudlyLegacyDeploymentSettlementFailureReason)) { return fail('INVALID_VALUE', `${pathArg}[${indexArg}]`); } return entryArg as TCloudlyLegacyDeploymentSettlementFailureReason; }); for (let index = 1; index < output.length; index++) { if (output[index - 1] >= output[index]) { fail('ORDERING_REQUIRED', `${pathArg}[${index}]`); } } return output; }; const normalizeSafeResultBase = ( valueArg: Record, pathArg: string, ): Omit => { const counts = normalizeMutationCounts(valueArg.counts, `${pathArg}.counts`); const classificationCounts = normalizeClassificationCounts( valueArg.classificationCounts, `${pathArg}.classificationCounts`, ); assertCountsMatchClassifications(counts, classificationCounts, `${pathArg}.counts.operationCount`); return { requestSha256: readSha256(valueArg.requestSha256, `${pathArg}.requestSha256`), planSha256: readSha256(valueArg.planSha256, `${pathArg}.planSha256`), settlementId: readIdentifier(valueArg.settlementId, `${pathArg}.settlementId`), sourceStateHmac: readStateHmac(valueArg.sourceStateHmac, `${pathArg}.sourceStateHmac`), finalStateHmac: readStateHmac(valueArg.finalStateHmac, `${pathArg}.finalStateHmac`), transactionSupported: readBoolean( valueArg.transactionSupported, `${pathArg}.transactionSupported`, ), counts, classificationCounts, }; }; export const normalizeCloudlyLegacyDeploymentSettlementCheckResult = ( valueArg: unknown, ): Readonly => { const value = readRecord(valueArg, 'checkResult'); const status = readLiteral(value.status, ['ready', 'blocked'], 'checkResult.status'); assertExactKeys(value, [ 'schemaVersion', 'kind', 'status', 'requestSha256', 'planSha256', 'settlementId', 'sourceStateHmac', 'finalStateHmac', 'transactionSupported', 'disposition', 'counts', 'classificationCounts', ...(status === 'blocked' ? ['failureReasons'] : []), 'checkedAt', ], 'checkResult'); if (value.schemaVersion !== 1 || value.kind !== 'cloudly-legacy-deployment-settlement-check-result') { fail('INVALID_VALUE', 'checkResult.kind'); } const base = normalizeSafeResultBase(value, 'checkResult'); const result: TCloudlyLegacyDeploymentSettlementCheckResultV1 = status === 'ready' ? { schemaVersion: 1, kind: 'cloudly-legacy-deployment-settlement-check-result', status, ...base, disposition: readLiteral( value.disposition, ['unapplied', 'exact-replay', 'no-op'], 'checkResult.disposition', ), checkedAt: readInteger(value.checkedAt, 'checkResult.checkedAt', 1), } : { schemaVersion: 1, kind: 'cloudly-legacy-deployment-settlement-check-result', status, ...base, disposition: readLiteral(value.disposition, ['unapplied'], 'checkResult.disposition'), failureReasons: normalizeFailureReasons(value.failureReasons, 'checkResult.failureReasons'), checkedAt: readInteger(value.checkedAt, 'checkResult.checkedAt', 1), }; const transactionFailurePresent = result.status === 'blocked' && result.failureReasons.includes('TRANSACTIONS_UNSUPPORTED'); if ((result.status === 'ready' && !result.transactionSupported) || (result.status === 'blocked' && transactionFailurePresent === result.transactionSupported)) { fail('CROSS_FIELD_MISMATCH', 'checkResult.transactionSupported'); } return finalize( result, cloudlyLegacyDeploymentSettlementLimits.maximumSafeResultBytes, 'checkResult', ); }; export const encodeCloudlyLegacyDeploymentSettlementCheckResult = ( valueArg: unknown, ): Uint8Array => encodeNormalized( normalizeCloudlyLegacyDeploymentSettlementCheckResult(valueArg), 'checkResult', ); export const encodeCloudlyLegacyDeploymentSettlementCheckResultHmacInput = ( valueArg: unknown, ): Uint8Array => frame( cloudlyLegacyDeploymentSettlementDomains.checkResultHmac, encodeNormalized( normalizeUnsignedAuthenticatedCheckResultInternal( valueArg, 'unsignedAuthenticatedCheckResult', ), 'unsignedAuthenticatedCheckResult', ), ); export const digestCloudlyLegacyDeploymentSettlementCheckResult = ( valueArg: unknown, ): string => digestBytes(encodeCloudlyLegacyDeploymentSettlementCheckResult(valueArg)); export const normalizeCloudlyLegacyDeploymentSettlementApplyResult = ( valueArg: unknown, ): Readonly => { const value = readRecord(valueArg, 'applyResult'); const status = readLiteral(value.status, ['completed', 'rejected'], 'applyResult.status'); assertExactKeys(value, [ 'schemaVersion', 'kind', 'status', 'requestSha256', 'planSha256', 'settlementId', 'sourceStateHmac', 'finalStateHmac', 'transactionSupported', 'disposition', 'counts', 'classificationCounts', ...(status === 'rejected' ? ['failureReasons', 'rejectedAt'] : ['completedAt']), ], 'applyResult'); if (value.schemaVersion !== 1 || value.kind !== 'cloudly-legacy-deployment-settlement-apply-result') { fail('INVALID_VALUE', 'applyResult.kind'); } const base = normalizeSafeResultBase(value, 'applyResult'); const result: TCloudlyLegacyDeploymentSettlementApplyResultV1 = status === 'completed' ? { schemaVersion: 1, kind: 'cloudly-legacy-deployment-settlement-apply-result', status, ...base, disposition: readLiteral( value.disposition, ['applied', 'exact-replay', 'no-op'], 'applyResult.disposition', ), completedAt: readInteger(value.completedAt, 'applyResult.completedAt', 1), } : { schemaVersion: 1, kind: 'cloudly-legacy-deployment-settlement-apply-result', status, ...base, disposition: readLiteral(value.disposition, ['unapplied'], 'applyResult.disposition'), failureReasons: normalizeFailureReasons(value.failureReasons, 'applyResult.failureReasons'), rejectedAt: readInteger(value.rejectedAt, 'applyResult.rejectedAt', 1), }; const transactionFailurePresent = result.status === 'rejected' && result.failureReasons.includes('TRANSACTIONS_UNSUPPORTED'); if ((result.status === 'completed' && !result.transactionSupported) || (result.status === 'rejected' && transactionFailurePresent === result.transactionSupported)) { fail('CROSS_FIELD_MISMATCH', 'applyResult.transactionSupported'); } return finalize( result, cloudlyLegacyDeploymentSettlementLimits.maximumSafeResultBytes, 'applyResult', ); }; export const encodeCloudlyLegacyDeploymentSettlementApplyResult = ( valueArg: unknown, ): Uint8Array => encodeNormalized( normalizeCloudlyLegacyDeploymentSettlementApplyResult(valueArg), 'applyResult', ); export const encodeCloudlyLegacyDeploymentSettlementApplyResultHmacInput = ( valueArg: unknown, ): Uint8Array => frame( cloudlyLegacyDeploymentSettlementDomains.applyResultHmac, encodeNormalized( normalizeUnsignedAuthenticatedApplyResultInternal( valueArg, 'unsignedAuthenticatedApplyResult', ), 'unsignedAuthenticatedApplyResult', ), ); export const digestCloudlyLegacyDeploymentSettlementApplyResult = ( valueArg: unknown, ): string => digestBytes(encodeCloudlyLegacyDeploymentSettlementApplyResult(valueArg)); const rehearsalBindingKeys = [ 'schemaVersion', 'kind', 'settlementId', 'runId', 'rehearsalId', 'scratchServiceId', 'allocationId', 'allocationGeneration', 'allocationBindingSha256', 'allocationReceiptSha256', 'backupId', 'backupSnapshotIdSha256', 'backupProofSha256', 'sourceDataSha256', 'restoredDataSha256', 'digestProofSha256', 'targetImageDigest', 'targetVersion', 'targetManifestSha256', 'targetConfigSha256', ] as const; const normalizeRehearsalBindingInternal = ( valueArg: unknown, pathArg: string, ): ICloudlyLegacyDeploymentSettlementRehearsalBindingV1 => { const value = readRecord(valueArg, pathArg); assertExactKeys(value, rehearsalBindingKeys, pathArg); if (value.schemaVersion !== 1 || value.kind !== 'cloudly-legacy-deployment-settlement-rehearsal-binding') { fail('INVALID_VALUE', `${pathArg}.kind`); } const sourceDataSha256 = readSha256(value.sourceDataSha256, `${pathArg}.sourceDataSha256`); const restoredDataSha256 = readSha256( value.restoredDataSha256, `${pathArg}.restoredDataSha256`, ); if (sourceDataSha256 !== restoredDataSha256) { fail('CROSS_FIELD_MISMATCH', `${pathArg}.restoredDataSha256`); } return { schemaVersion: 1, kind: 'cloudly-legacy-deployment-settlement-rehearsal-binding', settlementId: readIdentifier(value.settlementId, `${pathArg}.settlementId`), runId: readIdentifier(value.runId, `${pathArg}.runId`), rehearsalId: readIdentifier(value.rehearsalId, `${pathArg}.rehearsalId`), scratchServiceId: readIdentifier(value.scratchServiceId, `${pathArg}.scratchServiceId`), allocationId: readIdentifier(value.allocationId, `${pathArg}.allocationId`), allocationGeneration: readInteger( value.allocationGeneration, `${pathArg}.allocationGeneration`, 1, ), allocationBindingSha256: readSha256( value.allocationBindingSha256, `${pathArg}.allocationBindingSha256`, ), allocationReceiptSha256: readSha256( value.allocationReceiptSha256, `${pathArg}.allocationReceiptSha256`, ), backupId: readIdentifier(value.backupId, `${pathArg}.backupId`), backupSnapshotIdSha256: readSha256( value.backupSnapshotIdSha256, `${pathArg}.backupSnapshotIdSha256`, ), backupProofSha256: readSha256(value.backupProofSha256, `${pathArg}.backupProofSha256`), sourceDataSha256, restoredDataSha256, digestProofSha256: readSha256(value.digestProofSha256, `${pathArg}.digestProofSha256`), targetImageDigest: readOciDigest(value.targetImageDigest, `${pathArg}.targetImageDigest`), targetVersion: readIdentifier(value.targetVersion, `${pathArg}.targetVersion`), targetManifestSha256: readSha256( value.targetManifestSha256, `${pathArg}.targetManifestSha256`, ), targetConfigSha256: readSha256(value.targetConfigSha256, `${pathArg}.targetConfigSha256`), }; }; export const normalizeCloudlyLegacyDeploymentSettlementRehearsalBinding = ( valueArg: unknown, ): Readonly => finalize( normalizeRehearsalBindingInternal(valueArg, 'rehearsalBinding'), cloudlyLegacyDeploymentSettlementLimits.maximumAuthorityBytes, 'rehearsalBinding', ); export const encodeCloudlyLegacyDeploymentSettlementRehearsalBinding = ( valueArg: unknown, ): Uint8Array => encodeNormalized( normalizeCloudlyLegacyDeploymentSettlementRehearsalBinding(valueArg), 'rehearsalBinding', ); export const encodeCloudlyLegacyDeploymentSettlementRehearsalBindingHmacInput = ( valueArg: unknown, ): Uint8Array => frame( cloudlyLegacyDeploymentSettlementDomains.rehearsalBindingHmac, encodeNormalized( normalizeUnsignedAuthenticatedRehearsalBindingInternal( valueArg, 'unsignedAuthenticatedRehearsalBinding', ), 'unsignedAuthenticatedRehearsalBinding', ), ); export const digestCloudlyLegacyDeploymentSettlementRehearsalBinding = ( valueArg: unknown, ): string => digestBytes(encodeCloudlyLegacyDeploymentSettlementRehearsalBinding(valueArg)); export const normalizeCloudlyLegacyDeploymentSettlementProductionRequest = ( valueArg: unknown, ): Readonly => { const value = readRecord(valueArg, 'productionRequest'); assertExactKeys(value, [ 'schemaVersion', 'kind', 'authority', 'plan', 'planSha256', 'rehearsalBinding', 'rehearsalBindingSha256', 'requestedAt', ], 'productionRequest'); if (value.schemaVersion !== 1 || value.kind !== 'cloudly-legacy-deployment-settlement-production-request') { fail('INVALID_VALUE', 'productionRequest.kind'); } const authority = normalizeAuthorityReferenceInternal( value.authority, 'productionRequest.authority', ); const plan = normalizeCloudlyLegacyDeploymentSettlementPlan(value.plan); const planSha256 = readSha256(value.planSha256, 'productionRequest.planSha256'); const rehearsalBinding = normalizeRehearsalBindingInternal( value.rehearsalBinding, 'productionRequest.rehearsalBinding', ); const rehearsalBindingSha256 = readSha256( value.rehearsalBindingSha256, 'productionRequest.rehearsalBindingSha256', ); if (canonicalize(authority, 'productionRequest.authority') !== canonicalize(plan.authority, 'productionRequest.plan.authority')) { fail('CROSS_FIELD_MISMATCH', 'productionRequest.authority'); } if (planSha256 !== digestCloudlyLegacyDeploymentSettlementPlan(plan)) { fail('CROSS_FIELD_MISMATCH', 'productionRequest.planSha256'); } if (rehearsalBindingSha256 !== digestCloudlyLegacyDeploymentSettlementRehearsalBinding(rehearsalBinding)) { fail('CROSS_FIELD_MISMATCH', 'productionRequest.rehearsalBindingSha256'); } if (plan.settlementId !== rehearsalBinding.settlementId) { fail('CROSS_FIELD_MISMATCH', 'productionRequest.rehearsalBinding.settlementId'); } const requestedAt = readInteger(value.requestedAt, 'productionRequest.requestedAt', 1); if (requestedAt < plan.effectiveAt) { fail('CROSS_FIELD_MISMATCH', 'productionRequest.requestedAt'); } return finalize({ schemaVersion: 1, kind: 'cloudly-legacy-deployment-settlement-production-request', authority, plan, planSha256, rehearsalBinding, rehearsalBindingSha256, requestedAt, }, cloudlyLegacyDeploymentSettlementLimits.maximumAuthenticatedArtifactBytes, 'productionRequest'); }; export const encodeCloudlyLegacyDeploymentSettlementProductionRequest = ( valueArg: unknown, ): Uint8Array => encodeNormalized( normalizeCloudlyLegacyDeploymentSettlementProductionRequest(valueArg), 'productionRequest', ); export const digestCloudlyLegacyDeploymentSettlementProductionRequest = ( valueArg: unknown, ): string => digestBytes(encodeCloudlyLegacyDeploymentSettlementProductionRequest(valueArg)); const stableOutcomeKeys = [ 'schemaVersion', 'kind', 'settlementId', 'runId', 'rehearsalBindingSha256', 'effectiveAt', 'planSha256', 'sourceStateHmac', 'finalStateHmac', 'settlements', 'counts', 'classificationCounts', ] as const; const normalizeStableOutcomeInternal = ( valueArg: unknown, pathArg: string, ): ICloudlyLegacyDeploymentSettlementStableOutcomeV1 => { const value = readRecord(valueArg, pathArg); assertExactKeys(value, stableOutcomeKeys, pathArg); if (value.schemaVersion !== 1 || value.kind !== 'cloudly-legacy-deployment-settlement-stable-outcome') { fail('INVALID_VALUE', `${pathArg}.kind`); } const counts = normalizeMutationCounts(value.counts, `${pathArg}.counts`); const classificationCounts = normalizeClassificationCounts( value.classificationCounts, `${pathArg}.classificationCounts`, ); assertCountsMatchClassifications(counts, classificationCounts, `${pathArg}.counts.operationCount`); const settlements = readArray( value.settlements, `${pathArg}.settlements`, cloudlyLegacyDeploymentSettlementLimits.maximumOperations, ).map((entryArg, indexArg) => { const entryPath = `${pathArg}.settlements[${indexArg}]`; const entry = readRecord(entryArg, entryPath); assertExactKeys(entry, ['operationId', 'finalRevision', 'finalDocumentHmac'], entryPath); return { operationId: readIdentifier(entry.operationId, `${entryPath}.operationId`), finalRevision: readInteger(entry.finalRevision, `${entryPath}.finalRevision`, 1), finalDocumentHmac: readStateHmac( entry.finalDocumentHmac, `${entryPath}.finalDocumentHmac`, ), }; }); for (let index = 1; index < settlements.length; index++) { if (settlements[index - 1].operationId >= settlements[index].operationId) { fail('ORDERING_REQUIRED', `${pathArg}.settlements[${index}].operationId`); } } if (settlements.length !== counts.operationCount) { fail('CROSS_FIELD_MISMATCH', `${pathArg}.settlements`); } return { schemaVersion: 1, kind: 'cloudly-legacy-deployment-settlement-stable-outcome', settlementId: readIdentifier(value.settlementId, `${pathArg}.settlementId`), runId: readIdentifier(value.runId, `${pathArg}.runId`), rehearsalBindingSha256: readSha256( value.rehearsalBindingSha256, `${pathArg}.rehearsalBindingSha256`, ), effectiveAt: readInteger(value.effectiveAt, `${pathArg}.effectiveAt`, 1), planSha256: readSha256(value.planSha256, `${pathArg}.planSha256`), sourceStateHmac: readStateHmac(value.sourceStateHmac, `${pathArg}.sourceStateHmac`), finalStateHmac: readStateHmac(value.finalStateHmac, `${pathArg}.finalStateHmac`), settlements, counts, classificationCounts, }; }; export const normalizeCloudlyLegacyDeploymentSettlementStableOutcome = ( valueArg: unknown, ): Readonly => finalize( normalizeStableOutcomeInternal(valueArg, 'stableOutcome'), cloudlyLegacyDeploymentSettlementLimits.maximumReceiptBytes, 'stableOutcome', ); export const encodeCloudlyLegacyDeploymentSettlementStableOutcome = ( valueArg: unknown, ): Uint8Array => encodeNormalized( normalizeCloudlyLegacyDeploymentSettlementStableOutcome(valueArg), 'stableOutcome', ); export const encodeCloudlyLegacyDeploymentSettlementStableOutcomeHmacInput = ( valueArg: unknown, ): Uint8Array => frame( cloudlyLegacyDeploymentSettlementDomains.stableOutcomeHmac, encodeNormalized( normalizeUnsignedAuthenticatedStableOutcomeInternal( valueArg, 'unsignedAuthenticatedStableOutcome', ), 'unsignedAuthenticatedStableOutcome', ), ); export const digestCloudlyLegacyDeploymentSettlementStableOutcome = ( valueArg: unknown, ): string => digestBytes(encodeCloudlyLegacyDeploymentSettlementStableOutcome(valueArg)); type TAuthenticatedSettlementArtifactKind = | 'authenticated-cloudly-legacy-deployment-settlement-rehearsal-binding' | 'authenticated-cloudly-legacy-deployment-settlement-plan' | 'authenticated-cloudly-legacy-deployment-settlement-production-request' | 'authenticated-cloudly-legacy-deployment-settlement-check-result' | 'authenticated-cloudly-legacy-deployment-settlement-apply-result' | 'authenticated-cloudly-legacy-deployment-settlement-stable-outcome'; interface IUnsignedAuthenticatedSettlementArtifact { schemaVersion: 1; kind: TAuthenticatedSettlementArtifactKind; authority: ICloudlyLegacyDeploymentSettlementAuthorityReferenceV1; payload: TPayload; payloadSha256: string; } const authenticatedArtifactKeys = [ 'schemaVersion', 'kind', 'authority', 'payload', 'payloadSha256', 'mac', ] as const; const unsignedAuthenticatedArtifactKeys = authenticatedArtifactKeys.filter( (keyArg) => keyArg !== 'mac', ); const normalizeUnsignedAuthenticatedArtifactInternal = ( valueArg: unknown, pathArg: string, kindArg: TAuthenticatedSettlementArtifactKind, normalizePayloadArg: (valueArg: unknown) => Readonly, getPayloadAuthorityArg?: ( payloadArg: Readonly, ) => ICloudlyLegacyDeploymentSettlementAuthorityReferenceV1, ): IUnsignedAuthenticatedSettlementArtifact => { const value = readRecord(valueArg, pathArg); assertExactKeys(value, unsignedAuthenticatedArtifactKeys, pathArg); if (value.schemaVersion !== 1 || value.kind !== kindArg) { fail('INVALID_VALUE', `${pathArg}.kind`); } const authority = normalizeAuthorityReferenceInternal(value.authority, `${pathArg}.authority`); const payload = normalizePayloadArg(value.payload); const payloadSha256 = readSha256(value.payloadSha256, `${pathArg}.payloadSha256`); if (payloadSha256 !== digestBytes(encodeNormalized(payload, `${pathArg}.payload`))) { fail('CROSS_FIELD_MISMATCH', `${pathArg}.payloadSha256`); } if (getPayloadAuthorityArg && canonicalize(authority, `${pathArg}.authority`) !== canonicalize(getPayloadAuthorityArg(payload), `${pathArg}.payload.authority`)) { fail('CROSS_FIELD_MISMATCH', `${pathArg}.authority`); } return { schemaVersion: 1, kind: kindArg, authority, payload: payload as TPayload, payloadSha256, }; }; const normalizeAuthenticatedArtifactInternal = ( valueArg: unknown, pathArg: string, kindArg: TAuthenticatedSettlementArtifactKind, normalizePayloadArg: (valueArg: unknown) => Readonly, getPayloadAuthorityArg?: ( payloadArg: Readonly, ) => ICloudlyLegacyDeploymentSettlementAuthorityReferenceV1, ): IUnsignedAuthenticatedSettlementArtifact & { mac: string } => { const value = readRecord(valueArg, pathArg); assertExactKeys(value, authenticatedArtifactKeys, pathArg); const unsignedInput = Object.fromEntries(unsignedAuthenticatedArtifactKeys.map((keyArg) => [ keyArg, value[keyArg], ])); return { ...normalizeUnsignedAuthenticatedArtifactInternal( unsignedInput, `${pathArg}.unsigned`, kindArg, normalizePayloadArg, getPayloadAuthorityArg, ), mac: readMac(value.mac, `${pathArg}.mac`), }; }; const normalizeUnsignedAuthenticatedRehearsalBindingInternal = ( valueArg: unknown, pathArg: string, ): TUnsignedAuthenticatedCloudlyLegacyDeploymentSettlementRehearsalBindingV1 => ( normalizeUnsignedAuthenticatedArtifactInternal( valueArg, pathArg, 'authenticated-cloudly-legacy-deployment-settlement-rehearsal-binding', normalizeCloudlyLegacyDeploymentSettlementRehearsalBinding, ) as TUnsignedAuthenticatedCloudlyLegacyDeploymentSettlementRehearsalBindingV1 ); const normalizeUnsignedAuthenticatedPlanInternal = ( valueArg: unknown, pathArg: string, ): TUnsignedAuthenticatedCloudlyLegacyDeploymentSettlementPlanV1 => ( normalizeUnsignedAuthenticatedArtifactInternal( valueArg, pathArg, 'authenticated-cloudly-legacy-deployment-settlement-plan', normalizeCloudlyLegacyDeploymentSettlementPlan, (payloadArg) => payloadArg.authority, ) as TUnsignedAuthenticatedCloudlyLegacyDeploymentSettlementPlanV1 ); const normalizeUnsignedAuthenticatedProductionRequestInternal = ( valueArg: unknown, pathArg: string, ): TUnsignedAuthenticatedCloudlyLegacyDeploymentSettlementProductionRequestV1 => ( normalizeUnsignedAuthenticatedArtifactInternal( valueArg, pathArg, 'authenticated-cloudly-legacy-deployment-settlement-production-request', normalizeCloudlyLegacyDeploymentSettlementProductionRequest, (payloadArg) => payloadArg.authority, ) as TUnsignedAuthenticatedCloudlyLegacyDeploymentSettlementProductionRequestV1 ); const normalizeUnsignedAuthenticatedCheckResultInternal = ( valueArg: unknown, pathArg: string, ): TUnsignedAuthenticatedCloudlyLegacyDeploymentSettlementCheckResultV1 => ( normalizeUnsignedAuthenticatedArtifactInternal( valueArg, pathArg, 'authenticated-cloudly-legacy-deployment-settlement-check-result', normalizeCloudlyLegacyDeploymentSettlementCheckResult, ) as TUnsignedAuthenticatedCloudlyLegacyDeploymentSettlementCheckResultV1 ); const normalizeUnsignedAuthenticatedApplyResultInternal = ( valueArg: unknown, pathArg: string, ): TUnsignedAuthenticatedCloudlyLegacyDeploymentSettlementApplyResultV1 => ( normalizeUnsignedAuthenticatedArtifactInternal( valueArg, pathArg, 'authenticated-cloudly-legacy-deployment-settlement-apply-result', normalizeCloudlyLegacyDeploymentSettlementApplyResult, ) as TUnsignedAuthenticatedCloudlyLegacyDeploymentSettlementApplyResultV1 ); const normalizeUnsignedAuthenticatedStableOutcomeInternal = ( valueArg: unknown, pathArg: string, ): TUnsignedAuthenticatedCloudlyLegacyDeploymentSettlementStableOutcomeV1 => ( normalizeUnsignedAuthenticatedArtifactInternal( valueArg, pathArg, 'authenticated-cloudly-legacy-deployment-settlement-stable-outcome', normalizeCloudlyLegacyDeploymentSettlementStableOutcome, ) as TUnsignedAuthenticatedCloudlyLegacyDeploymentSettlementStableOutcomeV1 ); const finalizeAuthenticatedArtifact = (valueArg: T, pathArg: string): Readonly => finalize( valueArg, cloudlyLegacyDeploymentSettlementLimits.maximumAuthenticatedArtifactBytes, pathArg, ); /** Structural only. Use the async ForAuthority variant to authenticate its MAC. */ export const normalizeCloudlyLegacyDeploymentSettlementAuthenticatedRehearsalBindingStructure = ( valueArg: unknown, ): Readonly => ( finalizeAuthenticatedArtifact(normalizeAuthenticatedArtifactInternal( valueArg, 'authenticatedRehearsalBinding', 'authenticated-cloudly-legacy-deployment-settlement-rehearsal-binding', normalizeCloudlyLegacyDeploymentSettlementRehearsalBinding, ) as IAuthenticatedCloudlyLegacyDeploymentSettlementRehearsalBindingV1, 'authenticatedRehearsalBinding') ); export const normalizeCloudlyLegacyDeploymentSettlementAuthenticatedPlanStructure = ( valueArg: unknown, ): Readonly => ( finalizeAuthenticatedArtifact(normalizeAuthenticatedArtifactInternal( valueArg, 'authenticatedPlan', 'authenticated-cloudly-legacy-deployment-settlement-plan', normalizeCloudlyLegacyDeploymentSettlementPlan, (payloadArg) => payloadArg.authority, ) as IAuthenticatedCloudlyLegacyDeploymentSettlementPlanV1, 'authenticatedPlan') ); export const normalizeCloudlyLegacyDeploymentSettlementAuthenticatedProductionRequestStructure = ( valueArg: unknown, ): Readonly => ( finalizeAuthenticatedArtifact(normalizeAuthenticatedArtifactInternal( valueArg, 'authenticatedProductionRequest', 'authenticated-cloudly-legacy-deployment-settlement-production-request', normalizeCloudlyLegacyDeploymentSettlementProductionRequest, (payloadArg) => payloadArg.authority, ) as IAuthenticatedCloudlyLegacyDeploymentSettlementProductionRequestV1, 'authenticatedProductionRequest') ); export const normalizeCloudlyLegacyDeploymentSettlementAuthenticatedCheckResultStructure = ( valueArg: unknown, ): Readonly => ( finalizeAuthenticatedArtifact(normalizeAuthenticatedArtifactInternal( valueArg, 'authenticatedCheckResult', 'authenticated-cloudly-legacy-deployment-settlement-check-result', normalizeCloudlyLegacyDeploymentSettlementCheckResult, ) as IAuthenticatedCloudlyLegacyDeploymentSettlementCheckResultV1, 'authenticatedCheckResult') ); export const normalizeCloudlyLegacyDeploymentSettlementAuthenticatedApplyResultStructure = ( valueArg: unknown, ): Readonly => ( finalizeAuthenticatedArtifact(normalizeAuthenticatedArtifactInternal( valueArg, 'authenticatedApplyResult', 'authenticated-cloudly-legacy-deployment-settlement-apply-result', normalizeCloudlyLegacyDeploymentSettlementApplyResult, ) as IAuthenticatedCloudlyLegacyDeploymentSettlementApplyResultV1, 'authenticatedApplyResult') ); export const normalizeCloudlyLegacyDeploymentSettlementAuthenticatedStableOutcomeStructure = ( valueArg: unknown, ): Readonly => ( finalizeAuthenticatedArtifact(normalizeAuthenticatedArtifactInternal( valueArg, 'authenticatedStableOutcome', 'authenticated-cloudly-legacy-deployment-settlement-stable-outcome', normalizeCloudlyLegacyDeploymentSettlementStableOutcome, ) as IAuthenticatedCloudlyLegacyDeploymentSettlementStableOutcomeV1, 'authenticatedStableOutcome') ); export const encodeCloudlyLegacyDeploymentSettlementProductionRequestHmacInput = ( valueArg: unknown, ): Uint8Array => frame( cloudlyLegacyDeploymentSettlementDomains.productionRequestHmac, encodeNormalized( normalizeUnsignedAuthenticatedProductionRequestInternal( valueArg, 'unsignedAuthenticatedProductionRequest', ), 'unsignedAuthenticatedProductionRequest', ), ); const encodeAuthenticatedArtifact = ( valueArg: unknown, normalizeArg: (valueArg: unknown) => Readonly, pathArg: string, ): Uint8Array => encodeNormalized(normalizeArg(valueArg), pathArg); export const encodeAuthenticatedCloudlyLegacyDeploymentSettlementRehearsalBinding = ( valueArg: unknown, ): Uint8Array => encodeAuthenticatedArtifact( valueArg, normalizeCloudlyLegacyDeploymentSettlementAuthenticatedRehearsalBindingStructure, 'authenticatedRehearsalBinding', ); export const encodeAuthenticatedCloudlyLegacyDeploymentSettlementPlan = ( valueArg: unknown, ): Uint8Array => encodeAuthenticatedArtifact( valueArg, normalizeCloudlyLegacyDeploymentSettlementAuthenticatedPlanStructure, 'authenticatedPlan', ); export const encodeAuthenticatedCloudlyLegacyDeploymentSettlementProductionRequest = ( valueArg: unknown, ): Uint8Array => encodeAuthenticatedArtifact( valueArg, normalizeCloudlyLegacyDeploymentSettlementAuthenticatedProductionRequestStructure, 'authenticatedProductionRequest', ); export const encodeAuthenticatedCloudlyLegacyDeploymentSettlementCheckResult = ( valueArg: unknown, ): Uint8Array => encodeAuthenticatedArtifact( valueArg, normalizeCloudlyLegacyDeploymentSettlementAuthenticatedCheckResultStructure, 'authenticatedCheckResult', ); export const encodeAuthenticatedCloudlyLegacyDeploymentSettlementApplyResult = ( valueArg: unknown, ): Uint8Array => encodeAuthenticatedArtifact( valueArg, normalizeCloudlyLegacyDeploymentSettlementAuthenticatedApplyResultStructure, 'authenticatedApplyResult', ); export const encodeAuthenticatedCloudlyLegacyDeploymentSettlementStableOutcome = ( valueArg: unknown, ): Uint8Array => encodeAuthenticatedArtifact( valueArg, normalizeCloudlyLegacyDeploymentSettlementAuthenticatedStableOutcomeStructure, 'authenticatedStableOutcome', ); export const digestAuthenticatedCloudlyLegacyDeploymentSettlementRehearsalBinding = ( valueArg: unknown, ): string => digestBytes( encodeAuthenticatedCloudlyLegacyDeploymentSettlementRehearsalBinding(valueArg), ); export const digestAuthenticatedCloudlyLegacyDeploymentSettlementPlan = ( valueArg: unknown, ): string => digestBytes(encodeAuthenticatedCloudlyLegacyDeploymentSettlementPlan(valueArg)); export const digestAuthenticatedCloudlyLegacyDeploymentSettlementProductionRequest = ( valueArg: unknown, ): string => digestBytes( encodeAuthenticatedCloudlyLegacyDeploymentSettlementProductionRequest(valueArg), ); export const digestAuthenticatedCloudlyLegacyDeploymentSettlementCheckResult = ( valueArg: unknown, ): string => digestBytes( encodeAuthenticatedCloudlyLegacyDeploymentSettlementCheckResult(valueArg), ); export const digestAuthenticatedCloudlyLegacyDeploymentSettlementApplyResult = ( valueArg: unknown, ): string => digestBytes( encodeAuthenticatedCloudlyLegacyDeploymentSettlementApplyResult(valueArg), ); export const digestAuthenticatedCloudlyLegacyDeploymentSettlementStableOutcome = ( valueArg: unknown, ): string => digestBytes( encodeAuthenticatedCloudlyLegacyDeploymentSettlementStableOutcome(valueArg), ); const scratchReceiptKeys = [ 'schemaVersion', 'kind', 'authority', 'requestSha256', 'stableOutcome', 'stableOutcomeSha256', 'transactionCommitted', 'disposition', 'completedAt', 'payloadSha256', 'mac', ] as const; const scratchReceiptPayloadKeys = scratchReceiptKeys.filter((keyArg) => ( keyArg !== 'payloadSha256' && keyArg !== 'mac' )); const unsignedScratchReceiptKeys = scratchReceiptKeys.filter((keyArg) => keyArg !== 'mac'); const scratchReceiptPayload = ( valueArg: Omit, ): unknown => ({ schemaVersion: valueArg.schemaVersion, kind: valueArg.kind, authority: valueArg.authority, requestSha256: valueArg.requestSha256, stableOutcome: valueArg.stableOutcome, stableOutcomeSha256: valueArg.stableOutcomeSha256, transactionCommitted: valueArg.transactionCommitted, disposition: valueArg.disposition, completedAt: valueArg.completedAt, }); const normalizeScratchReceiptPayloadInternal = ( valueArg: unknown, pathArg: string, ): TCloudlyLegacyDeploymentSettlementScratchReceiptPayloadV1 => { const value = readRecord(valueArg, pathArg); assertExactKeys(value, scratchReceiptPayloadKeys, pathArg); if (value.schemaVersion !== 1 || value.kind !== 'cloudly-legacy-deployment-settlement-scratch-receipt' || value.transactionCommitted !== true) { fail('INVALID_VALUE', `${pathArg}.kind`); } const output = { schemaVersion: 1 as const, kind: 'cloudly-legacy-deployment-settlement-scratch-receipt' as const, authority: normalizeAuthorityReferenceInternal(value.authority, `${pathArg}.authority`), requestSha256: readSha256(value.requestSha256, `${pathArg}.requestSha256`), stableOutcome: normalizeStableOutcomeInternal(value.stableOutcome, `${pathArg}.stableOutcome`), stableOutcomeSha256: readSha256( value.stableOutcomeSha256, `${pathArg}.stableOutcomeSha256`, ), transactionCommitted: true as const, disposition: readLiteral( value.disposition, ['applied', 'exact-replay', 'no-op'], `${pathArg}.disposition`, ), completedAt: readInteger(value.completedAt, `${pathArg}.completedAt`, 1), }; if (output.stableOutcomeSha256 !== digestBytes(encodeNormalized(output.stableOutcome, `${pathArg}.stableOutcome`))) { fail('CROSS_FIELD_MISMATCH', `${pathArg}.stableOutcomeSha256`); } return output; }; const normalizeUnsignedScratchReceiptInternal = ( valueArg: unknown, pathArg: string, ): TCloudlyLegacyDeploymentSettlementUnsignedScratchReceiptV1 => { const value = readRecord(valueArg, pathArg); assertExactKeys(value, unsignedScratchReceiptKeys, pathArg); const payloadInput = Object.fromEntries(scratchReceiptPayloadKeys.map((keyArg) => [ keyArg, value[keyArg], ])); const payload = normalizeScratchReceiptPayloadInternal(payloadInput, `${pathArg}.payload`); const payloadSha256 = readSha256(value.payloadSha256, `${pathArg}.payloadSha256`); if (payloadSha256 !== digestBytes(encodeNormalized( scratchReceiptPayload(payload), `${pathArg}.payload`, ))) { fail('CROSS_FIELD_MISMATCH', `${pathArg}.payloadSha256`); } return { ...payload, payloadSha256 }; }; const normalizeScratchReceiptInternal = ( valueArg: unknown, pathArg: string, ): ICloudlyLegacyDeploymentSettlementScratchReceiptV1 => { const value = readRecord(valueArg, pathArg); assertExactKeys(value, scratchReceiptKeys, pathArg); const unsignedInput = Object.fromEntries(unsignedScratchReceiptKeys.map((keyArg) => [ keyArg, value[keyArg], ])); const unsigned = normalizeUnsignedScratchReceiptInternal(unsignedInput, `${pathArg}.unsigned`); return { ...unsigned, mac: readMac(value.mac, `${pathArg}.mac`), }; }; export const digestCloudlyLegacyDeploymentSettlementScratchReceiptPayload = ( valueArg: unknown, ): string => { const payload = normalizeScratchReceiptPayloadInternal(valueArg, 'scratchReceiptPayload'); return digestBytes(encodeNormalized( scratchReceiptPayload(payload), 'scratchReceiptPayload', )); }; export const normalizeCloudlyLegacyDeploymentSettlementScratchReceipt = ( valueArg: unknown, ): Readonly => finalize( normalizeScratchReceiptInternal(valueArg, 'scratchReceipt'), cloudlyLegacyDeploymentSettlementLimits.maximumReceiptBytes, 'scratchReceipt', ); export const encodeCloudlyLegacyDeploymentSettlementScratchReceipt = ( valueArg: unknown, ): Uint8Array => encodeNormalized( normalizeCloudlyLegacyDeploymentSettlementScratchReceipt(valueArg), 'scratchReceipt', ); export const encodeCloudlyLegacyDeploymentSettlementScratchReceiptHmacInput = ( valueArg: unknown, ): Uint8Array => { const authenticated = finalize( normalizeUnsignedScratchReceiptInternal(valueArg, 'unsignedScratchReceipt'), cloudlyLegacyDeploymentSettlementLimits.maximumReceiptBytes, 'unsignedScratchReceipt', ); return frame( cloudlyLegacyDeploymentSettlementDomains.scratchReceiptHmac, encodeNormalized(authenticated, 'scratchReceipt.authenticated'), ); }; export const digestCloudlyLegacyDeploymentSettlementScratchReceipt = ( valueArg: unknown, ): string => digestBytes(encodeCloudlyLegacyDeploymentSettlementScratchReceipt(valueArg)); const productionReceiptKeys = [ 'schemaVersion', 'kind', 'authority', 'requestSha256', 'scratchReceipt', 'scratchReceiptSha256', 'stableOutcome', 'stableOutcomeSha256', 'transactionCommitted', 'disposition', 'completedAt', 'payloadSha256', 'mac', ] as const; const productionReceiptPayloadKeys = productionReceiptKeys.filter((keyArg) => ( keyArg !== 'payloadSha256' && keyArg !== 'mac' )); const unsignedProductionReceiptKeys = productionReceiptKeys.filter((keyArg) => keyArg !== 'mac'); const productionReceiptPayload = ( valueArg: Omit, ): unknown => ({ schemaVersion: valueArg.schemaVersion, kind: valueArg.kind, authority: valueArg.authority, requestSha256: valueArg.requestSha256, scratchReceipt: valueArg.scratchReceipt, scratchReceiptSha256: valueArg.scratchReceiptSha256, stableOutcome: valueArg.stableOutcome, stableOutcomeSha256: valueArg.stableOutcomeSha256, transactionCommitted: valueArg.transactionCommitted, disposition: valueArg.disposition, completedAt: valueArg.completedAt, }); const normalizeProductionReceiptPayloadInternal = ( valueArg: unknown, pathArg: string, ): TCloudlyLegacyDeploymentSettlementProductionReceiptPayloadV1 => { const value = readRecord(valueArg, pathArg); assertExactKeys(value, productionReceiptPayloadKeys, pathArg); if (value.schemaVersion !== 1 || value.kind !== 'cloudly-legacy-deployment-settlement-production-receipt' || value.transactionCommitted !== true) { fail('INVALID_VALUE', `${pathArg}.kind`); } const scratchReceipt = normalizeScratchReceiptInternal( value.scratchReceipt, `${pathArg}.scratchReceipt`, ); const stableOutcome = normalizeStableOutcomeInternal( value.stableOutcome, `${pathArg}.stableOutcome`, ); const stableOutcomeSha256 = readSha256( value.stableOutcomeSha256, `${pathArg}.stableOutcomeSha256`, ); const authority = normalizeAuthorityReferenceInternal(value.authority, `${pathArg}.authority`); if (canonicalize(authority, `${pathArg}.authority`) !== canonicalize(scratchReceipt.authority, `${pathArg}.scratchReceipt.authority`)) { fail('CROSS_FIELD_MISMATCH', `${pathArg}.authority`); } const requestSha256 = readSha256(value.requestSha256, `${pathArg}.requestSha256`); const disposition = readLiteral( value.disposition, ['applied', 'exact-replay', 'no-op'], `${pathArg}.disposition`, ); const dispositionMatchesScratch = disposition === scratchReceipt.disposition || (scratchReceipt.disposition === 'applied' && disposition === 'exact-replay'); if (requestSha256 !== scratchReceipt.requestSha256 || !dispositionMatchesScratch) { fail('CROSS_FIELD_MISMATCH', `${pathArg}.scratchReceipt`); } if (canonicalize(stableOutcome, `${pathArg}.stableOutcome`) !== canonicalize(scratchReceipt.stableOutcome, `${pathArg}.scratchReceipt.stableOutcome`) || stableOutcomeSha256 !== scratchReceipt.stableOutcomeSha256 || stableOutcomeSha256 !== digestBytes(encodeNormalized(stableOutcome, `${pathArg}.stableOutcome`))) { fail('CROSS_FIELD_MISMATCH', `${pathArg}.stableOutcome`); } const scratchReceiptSha256 = readSha256( value.scratchReceiptSha256, `${pathArg}.scratchReceiptSha256`, ); if (scratchReceiptSha256 !== digestBytes(encodeNormalized(scratchReceipt, `${pathArg}.scratchReceipt`))) { fail('CROSS_FIELD_MISMATCH', `${pathArg}.scratchReceiptSha256`); } return { schemaVersion: 1, kind: 'cloudly-legacy-deployment-settlement-production-receipt', authority, requestSha256, scratchReceipt, scratchReceiptSha256, stableOutcome, stableOutcomeSha256, transactionCommitted: true, disposition, completedAt: readInteger( value.completedAt, `${pathArg}.completedAt`, scratchReceipt.completedAt, ), }; }; const normalizeUnsignedProductionReceiptInternal = ( valueArg: unknown, pathArg: string, ): TCloudlyLegacyDeploymentSettlementUnsignedProductionReceiptV1 => { const value = readRecord(valueArg, pathArg); assertExactKeys(value, unsignedProductionReceiptKeys, pathArg); const payloadInput = Object.fromEntries(productionReceiptPayloadKeys.map((keyArg) => [ keyArg, value[keyArg], ])); const payload = normalizeProductionReceiptPayloadInternal(payloadInput, `${pathArg}.payload`); const payloadSha256 = readSha256(value.payloadSha256, `${pathArg}.payloadSha256`); if (payloadSha256 !== digestBytes(encodeNormalized( productionReceiptPayload(payload), `${pathArg}.payload`, ))) { fail('CROSS_FIELD_MISMATCH', `${pathArg}.payloadSha256`); } return { ...payload, payloadSha256 }; }; export const digestCloudlyLegacyDeploymentSettlementProductionReceiptPayload = ( valueArg: unknown, ): string => { const payload = normalizeProductionReceiptPayloadInternal( valueArg, 'productionReceiptPayload', ); return digestBytes(encodeNormalized( productionReceiptPayload(payload), 'productionReceiptPayload', )); }; export const normalizeCloudlyLegacyDeploymentSettlementProductionReceipt = ( valueArg: unknown, ): Readonly => { const value = readRecord(valueArg, 'productionReceipt'); assertExactKeys(value, productionReceiptKeys, 'productionReceipt'); const unsignedInput = Object.fromEntries(unsignedProductionReceiptKeys.map((keyArg) => [ keyArg, value[keyArg], ])); const unsigned = normalizeUnsignedProductionReceiptInternal( unsignedInput, 'productionReceipt.unsigned', ); return finalize({ ...unsigned, mac: readMac(value.mac, 'productionReceipt.mac'), }, cloudlyLegacyDeploymentSettlementLimits.maximumReceiptBytes, 'productionReceipt'); }; export const encodeCloudlyLegacyDeploymentSettlementProductionReceipt = ( valueArg: unknown, ): Uint8Array => encodeNormalized( normalizeCloudlyLegacyDeploymentSettlementProductionReceipt(valueArg), 'productionReceipt', ); export const encodeCloudlyLegacyDeploymentSettlementProductionReceiptHmacInput = ( valueArg: unknown, ): Uint8Array => { const authenticated = finalize( normalizeUnsignedProductionReceiptInternal(valueArg, 'unsignedProductionReceipt'), cloudlyLegacyDeploymentSettlementLimits.maximumReceiptBytes, 'unsignedProductionReceipt', ); return frame( cloudlyLegacyDeploymentSettlementDomains.productionReceiptHmac, encodeNormalized(authenticated, 'productionReceipt.authenticated'), ); }; export const digestCloudlyLegacyDeploymentSettlementProductionReceipt = ( valueArg: unknown, ): string => digestBytes(encodeCloudlyLegacyDeploymentSettlementProductionReceipt(valueArg)); const withoutArtifactMac = ( artifactArg: TArtifact, ): Omit => { const { mac: _mac, ...unsigned } = artifactArg; return unsigned; }; const requireConsumerVerifiedHmac = async ( authorityArg: ICloudlyLegacyDeploymentSettlementAuthorityReferenceV1, domainArg: ICloudlyLegacyDeploymentSettlementHmacVerificationInputV1['domain'], hmacInputArg: Uint8Array, macArg: string, verifierArg: TCloudlyLegacyDeploymentSettlementHmacVerifier, pathArg: string, ): Promise => { let verified = false; try { verified = await verifierArg({ authority: authorityArg, domain: domainArg, hmacInput: new Uint8Array(hmacInputArg), mac: macArg, }); } catch { verified = false; } if (!verified) fail('INVALID_VALUE', pathArg); }; const assertAuthorityTimestamp = ( timestampArg: number, metadataArg: TCloudlyLegacyDeploymentSettlementAuthorityMetadataV1, pathArg: string, ): void => { if (timestampArg < metadataArg.issuedAt || timestampArg >= metadataArg.expiresAt) { fail('CROSS_FIELD_MISMATCH', pathArg); } }; const assertAuthorityReferenceMatchesMetadata = ( referenceArg: unknown, metadataArg: TCloudlyLegacyDeploymentSettlementAuthorityMetadataV1, pathArg: string, ): void => { try { normalizeCloudlyLegacyDeploymentSettlementAuthorityReferenceForMetadata( referenceArg, metadataArg, ); } catch { fail('CROSS_FIELD_MISMATCH', pathArg); } }; const assertRehearsalBindingMatchesAuthorityMetadata = ( bindingArg: ICloudlyLegacyDeploymentSettlementRehearsalBindingV1, metadataArg: TCloudlyLegacyDeploymentSettlementAuthorityMetadataV1, pathArg: string, ): void => { const expected = { settlementId: metadataArg.settlementId, runId: metadataArg.runId, rehearsalId: metadataArg.rehearsalId, scratchServiceId: metadataArg.scratchServiceId, allocationId: metadataArg.allocationId, allocationGeneration: metadataArg.allocationGeneration, allocationBindingSha256: metadataArg.allocationBindingSha256, allocationReceiptSha256: metadataArg.allocationReceiptSha256, backupId: metadataArg.backupId, backupSnapshotIdSha256: metadataArg.backupSnapshotIdSha256, backupProofSha256: metadataArg.backupProofSha256, sourceDataSha256: metadataArg.sourceDataSha256, restoredDataSha256: metadataArg.restoredDataSha256, digestProofSha256: metadataArg.digestProofSha256, targetImageDigest: metadataArg.targetImageDigest, targetVersion: metadataArg.targetVersion, targetManifestSha256: metadataArg.targetManifestSha256, targetConfigSha256: metadataArg.targetConfigSha256, }; const actual = { settlementId: bindingArg.settlementId, runId: bindingArg.runId, rehearsalId: bindingArg.rehearsalId, scratchServiceId: bindingArg.scratchServiceId, allocationId: bindingArg.allocationId, allocationGeneration: bindingArg.allocationGeneration, allocationBindingSha256: bindingArg.allocationBindingSha256, allocationReceiptSha256: bindingArg.allocationReceiptSha256, backupId: bindingArg.backupId, backupSnapshotIdSha256: bindingArg.backupSnapshotIdSha256, backupProofSha256: bindingArg.backupProofSha256, sourceDataSha256: bindingArg.sourceDataSha256, restoredDataSha256: bindingArg.restoredDataSha256, digestProofSha256: bindingArg.digestProofSha256, targetImageDigest: bindingArg.targetImageDigest, targetVersion: bindingArg.targetVersion, targetManifestSha256: bindingArg.targetManifestSha256, targetConfigSha256: bindingArg.targetConfigSha256, }; if (canonicalize(actual, pathArg) !== canonicalize(expected, `${pathArg}.expected`)) { fail('CROSS_FIELD_MISMATCH', pathArg); } }; export const normalizeCloudlyLegacyDeploymentSettlementRehearsalBindingForAuthority = ( bindingArg: unknown, metadataArg: unknown, ): Readonly => { const metadata = normalizeCloudlyLegacyDeploymentSettlementAuthorityMetadata(metadataArg); const binding = normalizeCloudlyLegacyDeploymentSettlementRehearsalBinding(bindingArg); assertRehearsalBindingMatchesAuthorityMetadata(binding, metadata, 'rehearsalBinding.authority'); return binding; }; export const normalizeCloudlyLegacyDeploymentSettlementPlanForAuthority = ( planArg: unknown, metadataArg: unknown, ): Readonly => { const metadata = normalizeCloudlyLegacyDeploymentSettlementAuthorityMetadata(metadataArg); const plan = normalizeCloudlyLegacyDeploymentSettlementPlan(planArg); assertAuthorityReferenceMatchesMetadata(plan.authority, metadata, 'plan.authority'); if (plan.settlementId !== metadata.settlementId) { fail('CROSS_FIELD_MISMATCH', 'plan.settlementId'); } assertAuthorityTimestamp(plan.effectiveAt, metadata, 'plan.effectiveAt'); return plan; }; export const normalizeCloudlyLegacyDeploymentSettlementProductionRequestForAuthority = ( requestArg: unknown, metadataArg: unknown, ): Readonly => { const metadata = normalizeCloudlyLegacyDeploymentSettlementAuthorityMetadata(metadataArg); const request = normalizeCloudlyLegacyDeploymentSettlementProductionRequest(requestArg); assertAuthorityReferenceMatchesMetadata( request.authority, metadata, 'productionRequest.authority', ); normalizeCloudlyLegacyDeploymentSettlementPlanForAuthority(request.plan, metadata); normalizeCloudlyLegacyDeploymentSettlementRehearsalBindingForAuthority( request.rehearsalBinding, metadata, ); assertAuthorityTimestamp(request.requestedAt, metadata, 'productionRequest.requestedAt'); return request; }; export const normalizeAuthenticatedCloudlyLegacyDeploymentSettlementRehearsalBindingForAuthority = async ( bindingArg: unknown, metadataArg: unknown, verifierArg: TCloudlyLegacyDeploymentSettlementHmacVerifier, ): Promise> => { const metadata = normalizeCloudlyLegacyDeploymentSettlementAuthorityMetadata(metadataArg); const binding = normalizeCloudlyLegacyDeploymentSettlementAuthenticatedRehearsalBindingStructure( bindingArg, ); assertAuthorityReferenceMatchesMetadata(binding.authority, metadata, 'rehearsalBinding.authority'); normalizeCloudlyLegacyDeploymentSettlementRehearsalBindingForAuthority( binding.payload, metadata, ); await requireConsumerVerifiedHmac( binding.authority, cloudlyLegacyDeploymentSettlementDomains.rehearsalBindingHmac, encodeCloudlyLegacyDeploymentSettlementRehearsalBindingHmacInput( withoutArtifactMac(binding), ), binding.mac, verifierArg, 'rehearsalBinding.mac', ); return binding; }; export const normalizeAuthenticatedCloudlyLegacyDeploymentSettlementPlanForAuthority = async ( planArg: unknown, metadataArg: unknown, verifierArg: TCloudlyLegacyDeploymentSettlementHmacVerifier, ): Promise> => { const metadata = normalizeCloudlyLegacyDeploymentSettlementAuthorityMetadata(metadataArg); const plan = normalizeCloudlyLegacyDeploymentSettlementAuthenticatedPlanStructure(planArg); assertAuthorityReferenceMatchesMetadata(plan.authority, metadata, 'plan.authority'); normalizeCloudlyLegacyDeploymentSettlementPlanForAuthority(plan.payload, metadata); await requireConsumerVerifiedHmac( plan.authority, cloudlyLegacyDeploymentSettlementDomains.planHmac, encodeCloudlyLegacyDeploymentSettlementPlanHmacInput(withoutArtifactMac(plan)), plan.mac, verifierArg, 'plan.mac', ); return plan; }; export const normalizeAuthenticatedCloudlyLegacyDeploymentSettlementProductionRequestForAuthority = async ( requestArg: unknown, metadataArg: unknown, verifierArg: TCloudlyLegacyDeploymentSettlementHmacVerifier, ): Promise> => { const metadata = normalizeCloudlyLegacyDeploymentSettlementAuthorityMetadata(metadataArg); const request = normalizeCloudlyLegacyDeploymentSettlementAuthenticatedProductionRequestStructure( requestArg, ); assertAuthorityReferenceMatchesMetadata( request.authority, metadata, 'productionRequest.authority', ); normalizeCloudlyLegacyDeploymentSettlementProductionRequestForAuthority( request.payload, metadata, ); await requireConsumerVerifiedHmac( request.authority, cloudlyLegacyDeploymentSettlementDomains.productionRequestHmac, encodeCloudlyLegacyDeploymentSettlementProductionRequestHmacInput( withoutArtifactMac(request), ), request.mac, verifierArg, 'productionRequest.mac', ); return request; }; export const normalizeAuthenticatedCloudlyLegacyDeploymentSettlementCheckResultForAuthority = async ( resultArg: unknown, metadataArg: unknown, requestArg: unknown, verifierArg: TCloudlyLegacyDeploymentSettlementHmacVerifier, ): Promise> => { const metadata = normalizeCloudlyLegacyDeploymentSettlementAuthorityMetadata(metadataArg); const request = await normalizeAuthenticatedCloudlyLegacyDeploymentSettlementProductionRequestForAuthority( requestArg, metadata, verifierArg, ); const result = normalizeCloudlyLegacyDeploymentSettlementAuthenticatedCheckResultStructureForRequest( resultArg, request, ); assertAuthorityReferenceMatchesMetadata(result.authority, metadata, 'checkResult.authority'); assertAuthorityTimestamp(result.payload.checkedAt, metadata, 'checkResult.checkedAt'); await requireConsumerVerifiedHmac( result.authority, cloudlyLegacyDeploymentSettlementDomains.checkResultHmac, encodeCloudlyLegacyDeploymentSettlementCheckResultHmacInput(withoutArtifactMac(result)), result.mac, verifierArg, 'checkResult.mac', ); return result; }; export const normalizeAuthenticatedCloudlyLegacyDeploymentSettlementApplyResultForAuthority = async ( resultArg: unknown, metadataArg: unknown, requestArg: unknown, verifierArg: TCloudlyLegacyDeploymentSettlementHmacVerifier, ): Promise> => { const metadata = normalizeCloudlyLegacyDeploymentSettlementAuthorityMetadata(metadataArg); const request = await normalizeAuthenticatedCloudlyLegacyDeploymentSettlementProductionRequestForAuthority( requestArg, metadata, verifierArg, ); const result = normalizeCloudlyLegacyDeploymentSettlementAuthenticatedApplyResultStructureForRequest( resultArg, request, ); assertAuthorityReferenceMatchesMetadata(result.authority, metadata, 'applyResult.authority'); assertAuthorityTimestamp( result.payload.status === 'completed' ? result.payload.completedAt : result.payload.rejectedAt, metadata, 'applyResult.completedAt', ); await requireConsumerVerifiedHmac( result.authority, cloudlyLegacyDeploymentSettlementDomains.applyResultHmac, encodeCloudlyLegacyDeploymentSettlementApplyResultHmacInput(withoutArtifactMac(result)), result.mac, verifierArg, 'applyResult.mac', ); return result; }; export const normalizeAuthenticatedCloudlyLegacyDeploymentSettlementStableOutcomeForAuthority = async ( outcomeArg: unknown, metadataArg: unknown, requestArg: unknown, verifierArg: TCloudlyLegacyDeploymentSettlementHmacVerifier, ): Promise> => { const metadata = normalizeCloudlyLegacyDeploymentSettlementAuthorityMetadata(metadataArg); const request = await normalizeAuthenticatedCloudlyLegacyDeploymentSettlementProductionRequestForAuthority( requestArg, metadata, verifierArg, ); const outcome = normalizeCloudlyLegacyDeploymentSettlementAuthenticatedStableOutcomeStructureForRequest( outcomeArg, request, ); assertAuthorityReferenceMatchesMetadata(outcome.authority, metadata, 'stableOutcome.authority'); if (outcome.payload.settlementId !== metadata.settlementId || outcome.payload.runId !== metadata.runId) { fail('CROSS_FIELD_MISMATCH', 'stableOutcome.authority'); } assertAuthorityTimestamp(outcome.payload.effectiveAt, metadata, 'stableOutcome.effectiveAt'); await requireConsumerVerifiedHmac( outcome.authority, cloudlyLegacyDeploymentSettlementDomains.stableOutcomeHmac, encodeCloudlyLegacyDeploymentSettlementStableOutcomeHmacInput( withoutArtifactMac(outcome), ), outcome.mac, verifierArg, 'stableOutcome.mac', ); return outcome; }; export const normalizeCloudlyLegacyDeploymentSettlementScratchReceiptForAuthority = async ( receiptArg: unknown, metadataArg: unknown, requestArg: unknown, verifierArg: TCloudlyLegacyDeploymentSettlementHmacVerifier, ): Promise> => { const metadata = normalizeCloudlyLegacyDeploymentSettlementAuthorityMetadata(metadataArg); const request = await normalizeAuthenticatedCloudlyLegacyDeploymentSettlementProductionRequestForAuthority( requestArg, metadata, verifierArg, ); const receipt = normalizeCloudlyLegacyDeploymentSettlementScratchReceiptStructureForRequest( receiptArg, request, ); assertAuthorityReferenceMatchesMetadata(receipt.authority, metadata, 'scratchReceipt.authority'); if (receipt.stableOutcome.settlementId !== metadata.settlementId || receipt.stableOutcome.runId !== metadata.runId) { fail('CROSS_FIELD_MISMATCH', 'scratchReceipt.stableOutcome'); } assertAuthorityTimestamp(receipt.stableOutcome.effectiveAt, metadata, 'scratchReceipt.effectiveAt'); assertAuthorityTimestamp(receipt.completedAt, metadata, 'scratchReceipt.completedAt'); await requireConsumerVerifiedHmac( receipt.authority, cloudlyLegacyDeploymentSettlementDomains.scratchReceiptHmac, encodeCloudlyLegacyDeploymentSettlementScratchReceiptHmacInput( withoutArtifactMac(receipt), ), receipt.mac, verifierArg, 'scratchReceipt.mac', ); return receipt; }; export const normalizeCloudlyLegacyDeploymentSettlementProductionReceiptForAuthority = async ( receiptArg: unknown, metadataArg: unknown, requestArg: unknown, verifierArg: TCloudlyLegacyDeploymentSettlementHmacVerifier, ): Promise> => { const metadata = normalizeCloudlyLegacyDeploymentSettlementAuthorityMetadata(metadataArg); const request = await normalizeAuthenticatedCloudlyLegacyDeploymentSettlementProductionRequestForAuthority( requestArg, metadata, verifierArg, ); const receipt = normalizeCloudlyLegacyDeploymentSettlementProductionReceiptStructureForRequest( receiptArg, request, ); assertAuthorityReferenceMatchesMetadata( receipt.authority, metadata, 'productionReceipt.authority', ); await normalizeCloudlyLegacyDeploymentSettlementScratchReceiptForAuthority( receipt.scratchReceipt, metadata, request, verifierArg, ); if (receipt.stableOutcome.settlementId !== metadata.settlementId || receipt.stableOutcome.runId !== metadata.runId) { fail('CROSS_FIELD_MISMATCH', 'productionReceipt.stableOutcome'); } assertAuthorityTimestamp(receipt.completedAt, metadata, 'productionReceipt.completedAt'); await requireConsumerVerifiedHmac( receipt.authority, cloudlyLegacyDeploymentSettlementDomains.productionReceiptHmac, encodeCloudlyLegacyDeploymentSettlementProductionReceiptHmacInput( withoutArtifactMac(receipt), ), receipt.mac, verifierArg, 'productionReceipt.mac', ); return receipt; }; const assertAuthenticatedAuthorityMatches = ( authorityArg: ICloudlyLegacyDeploymentSettlementAuthorityReferenceV1, expectedArg: ICloudlyLegacyDeploymentSettlementAuthorityReferenceV1, pathArg: string, ): void => { if (canonicalize(authorityArg, pathArg) !== canonicalize(expectedArg, `${pathArg}.expected`)) { fail('CROSS_FIELD_MISMATCH', pathArg); } }; const assertSummaryMatchesProductionRequest = ( summaryArg: ICloudlyLegacyDeploymentSettlementSafeResultBaseV1, requestArg: ICloudlyLegacyDeploymentSettlementProductionRequestV1, pathArg: string, ): void => { if (summaryArg.requestSha256 !== digestCloudlyLegacyDeploymentSettlementProductionRequest(requestArg) || summaryArg.planSha256 !== requestArg.planSha256 || summaryArg.settlementId !== requestArg.plan.settlementId || summaryArg.sourceStateHmac !== requestArg.plan.sourceStateHmac || summaryArg.finalStateHmac !== requestArg.plan.finalStateHmac || canonicalize(summaryArg.counts, `${pathArg}.counts`) !== canonicalize({ operationCount: requestArg.plan.operationCount, routeClaimsStabilized: requestArg.plan.entries.reduce( (sumArg, entryArg) => sumArg + entryArg.routeClaimsStabilized, 0, ), routeClaimsRemoved: requestArg.plan.entries.reduce( (sumArg, entryArg) => sumArg + entryArg.routeClaimsRemoved, 0, ), resourceClaimsRemoved: requestArg.plan.entries.reduce( (sumArg, entryArg) => sumArg + entryArg.resourceClaimsRemoved, 0, ), }, `${pathArg}.expectedCounts`) || canonicalize(summaryArg.classificationCounts, `${pathArg}.classificationCounts`) !== canonicalize( requestArg.plan.classificationCounts, `${pathArg}.expectedClassificationCounts`, )) { fail('CROSS_FIELD_MISMATCH', pathArg); } }; const assertStableOutcomeMatchesProductionRequest = ( stableOutcomeArg: ICloudlyLegacyDeploymentSettlementStableOutcomeV1, requestArg: ICloudlyLegacyDeploymentSettlementProductionRequestV1, pathArg: string, ): void => { const expectedSettlements: ICloudlyLegacyDeploymentSettlementStableOutcomeEntryV1[] = requestArg.plan.entries.map((entryArg) => ({ operationId: entryArg.operationId, finalRevision: entryArg.finalRevision, finalDocumentHmac: entryArg.finalDocumentHmac, })); if (stableOutcomeArg.settlementId !== requestArg.plan.settlementId || stableOutcomeArg.runId !== requestArg.rehearsalBinding.runId || stableOutcomeArg.rehearsalBindingSha256 !== requestArg.rehearsalBindingSha256 || stableOutcomeArg.effectiveAt !== requestArg.plan.effectiveAt || stableOutcomeArg.planSha256 !== requestArg.planSha256 || stableOutcomeArg.sourceStateHmac !== requestArg.plan.sourceStateHmac || stableOutcomeArg.finalStateHmac !== requestArg.plan.finalStateHmac || canonicalize(stableOutcomeArg.settlements, `${pathArg}.settlements`) !== canonicalize(expectedSettlements, `${pathArg}.expectedSettlements`)) { fail('CROSS_FIELD_MISMATCH', pathArg); } assertSummaryMatchesProductionRequest({ schemaVersion: 1, requestSha256: digestCloudlyLegacyDeploymentSettlementProductionRequest(requestArg), planSha256: stableOutcomeArg.planSha256, settlementId: stableOutcomeArg.settlementId, sourceStateHmac: stableOutcomeArg.sourceStateHmac, finalStateHmac: stableOutcomeArg.finalStateHmac, transactionSupported: true, counts: stableOutcomeArg.counts, classificationCounts: stableOutcomeArg.classificationCounts, }, requestArg, pathArg); }; /** Structural/request binding only; this function does not authenticate MACs. */ export const normalizeCloudlyLegacyDeploymentSettlementAuthenticatedCheckResultStructureForRequest = ( resultArg: unknown, requestArg: unknown, ): Readonly => { const request = normalizeCloudlyLegacyDeploymentSettlementAuthenticatedProductionRequestStructure( requestArg, ); const result = normalizeCloudlyLegacyDeploymentSettlementAuthenticatedCheckResultStructure(resultArg); assertAuthenticatedAuthorityMatches(result.authority, request.authority, 'checkResult.authority'); assertSummaryMatchesProductionRequest(result.payload, request.payload, 'checkResult.payload'); if (result.payload.checkedAt < request.payload.requestedAt) { fail('CROSS_FIELD_MISMATCH', 'checkResult.payload.checkedAt'); } return result; }; export const normalizeCloudlyLegacyDeploymentSettlementAuthenticatedApplyResultStructureForRequest = ( resultArg: unknown, requestArg: unknown, ): Readonly => { const request = normalizeCloudlyLegacyDeploymentSettlementAuthenticatedProductionRequestStructure( requestArg, ); const result = normalizeCloudlyLegacyDeploymentSettlementAuthenticatedApplyResultStructure(resultArg); assertAuthenticatedAuthorityMatches(result.authority, request.authority, 'applyResult.authority'); assertSummaryMatchesProductionRequest(result.payload, request.payload, 'applyResult.payload'); const resultAt = result.payload.status === 'completed' ? result.payload.completedAt : result.payload.rejectedAt; if (resultAt < request.payload.requestedAt) { fail('CROSS_FIELD_MISMATCH', 'applyResult.payload.completedAt'); } return result; }; export const normalizeCloudlyLegacyDeploymentSettlementAuthenticatedStableOutcomeStructureForRequest = ( outcomeArg: unknown, requestArg: unknown, ): Readonly => { const request = normalizeCloudlyLegacyDeploymentSettlementAuthenticatedProductionRequestStructure( requestArg, ); const outcome = normalizeCloudlyLegacyDeploymentSettlementAuthenticatedStableOutcomeStructure(outcomeArg); assertAuthenticatedAuthorityMatches( outcome.authority, request.authority, 'stableOutcome.authority', ); assertStableOutcomeMatchesProductionRequest( outcome.payload, request.payload, 'stableOutcome.payload', ); return outcome; }; /** Structural/request binding only; this function does not authenticate MACs. */ export const normalizeCloudlyLegacyDeploymentSettlementScratchReceiptStructureForRequest = ( receiptArg: unknown, requestArg: unknown, ): Readonly => { const request = normalizeCloudlyLegacyDeploymentSettlementAuthenticatedProductionRequestStructure( requestArg, ); const receipt = normalizeCloudlyLegacyDeploymentSettlementScratchReceipt(receiptArg); assertAuthenticatedAuthorityMatches(receipt.authority, request.authority, 'scratchReceipt.authority'); if (receipt.requestSha256 !== digestCloudlyLegacyDeploymentSettlementProductionRequest(request.payload) || receipt.completedAt < request.payload.requestedAt) { fail('CROSS_FIELD_MISMATCH', 'scratchReceipt.requestSha256'); } assertStableOutcomeMatchesProductionRequest( receipt.stableOutcome, request.payload, 'scratchReceipt.stableOutcome', ); return receipt; }; export const normalizeCloudlyLegacyDeploymentSettlementProductionReceiptStructureForRequest = ( receiptArg: unknown, requestArg: unknown, ): Readonly => { const request = normalizeCloudlyLegacyDeploymentSettlementAuthenticatedProductionRequestStructure( requestArg, ); const receipt = normalizeCloudlyLegacyDeploymentSettlementProductionReceipt(receiptArg); normalizeCloudlyLegacyDeploymentSettlementScratchReceiptStructureForRequest( receipt.scratchReceipt, request, ); assertAuthenticatedAuthorityMatches( receipt.authority, request.authority, 'productionReceipt.authority', ); if (receipt.requestSha256 !== digestCloudlyLegacyDeploymentSettlementProductionRequest(request.payload) || receipt.completedAt < request.payload.requestedAt) { fail('CROSS_FIELD_MISMATCH', 'productionReceipt.requestSha256'); } return receipt; }; export interface ICloudlyLegacyDeploymentSettlementRequestBundleV1 { schemaVersion: 1; kind: 'cloudly-legacy-deployment-settlement-request-bundle'; authenticatedRehearsalBinding: IAuthenticatedCloudlyLegacyDeploymentSettlementRehearsalBindingV1; authenticatedRequest: IAuthenticatedCloudlyLegacyDeploymentSettlementProductionRequestV1; } export type TCloudlyLegacyDeploymentSettlementExecutionPurpose = | 'scratch-rehearsal' | 'production'; export interface ICloudlyLegacyDeploymentSettlementExecutionAttemptIdentityV1 { schemaVersion: 1; kind: 'cloudly-legacy-deployment-settlement-execution-attempt-identity'; attemptId: string; purpose: TCloudlyLegacyDeploymentSettlementExecutionPurpose; operationId: string; settlementId: string; executionAuthority: ICloudlyLegacyDeploymentSettlementAuthorityReferenceV1; sourceAuthority: ICloudlyLegacyDeploymentSettlementAuthorityReferenceV1; authenticatedPlanSha256: string; requestBundleSha256: string; scratchReceiptSha256: string | null; } export type TCloudlyLegacyDeploymentSettlementScratchExecutionAttemptIdentityV1 = ICloudlyLegacyDeploymentSettlementExecutionAttemptIdentityV1 & { purpose: 'scratch-rehearsal'; scratchReceiptSha256: null; }; export type TCloudlyLegacyDeploymentSettlementProductionExecutionAttemptIdentityV1 = ICloudlyLegacyDeploymentSettlementExecutionAttemptIdentityV1 & { purpose: 'production'; scratchReceiptSha256: string; }; export type TCloudlyLegacyDeploymentSettlementExecutionAttemptIdentityV1 = | TCloudlyLegacyDeploymentSettlementScratchExecutionAttemptIdentityV1 | TCloudlyLegacyDeploymentSettlementProductionExecutionAttemptIdentityV1; export interface ICloudlyLegacyDeploymentSettlementExecutionAttemptPreparedV1 { schemaVersion: 1; kind: 'cloudly-legacy-deployment-settlement-execution-attempt-observation'; identity: TCloudlyLegacyDeploymentSettlementExecutionAttemptIdentityV1; state: 'prepared'; preparedAt: number; } export interface ICloudlyLegacyDeploymentSettlementExecutionAttemptCommittedV1 { schemaVersion: 1; kind: 'cloudly-legacy-deployment-settlement-execution-attempt-observation'; identity: TCloudlyLegacyDeploymentSettlementExecutionAttemptIdentityV1; state: 'committed'; preparedAt: number; resolvedAt: number; receiptSchemaVersion: 1 | 2; receiptSha256: string; } export interface ICloudlyLegacyDeploymentSettlementExecutionAttemptAbortedV1 { schemaVersion: 1; kind: 'cloudly-legacy-deployment-settlement-execution-attempt-observation'; identity: TCloudlyLegacyDeploymentSettlementExecutionAttemptIdentityV1; state: 'aborted'; preparedAt: number; resolvedAt: number; } export type TCloudlyLegacyDeploymentSettlementExecutionAttemptObservationV1 = | ICloudlyLegacyDeploymentSettlementExecutionAttemptPreparedV1 | ICloudlyLegacyDeploymentSettlementExecutionAttemptCommittedV1 | ICloudlyLegacyDeploymentSettlementExecutionAttemptAbortedV1; const requestBundleKeys = [ 'schemaVersion', 'kind', 'authenticatedRehearsalBinding', 'authenticatedRequest', ] as const; export const normalizeCloudlyLegacyDeploymentSettlementRequestBundle = ( valueArg: unknown, ): Readonly => { const value = readRecord(valueArg, 'requestBundle'); assertExactKeys(value, requestBundleKeys, 'requestBundle'); if (value.schemaVersion !== 1 || value.kind !== 'cloudly-legacy-deployment-settlement-request-bundle') { fail('INVALID_VALUE', 'requestBundle.kind'); } const authenticatedRehearsalBinding = normalizeCloudlyLegacyDeploymentSettlementAuthenticatedRehearsalBindingStructure( value.authenticatedRehearsalBinding, ); const authenticatedRequest = normalizeCloudlyLegacyDeploymentSettlementAuthenticatedProductionRequestStructure( value.authenticatedRequest, ); if (canonicalize(authenticatedRehearsalBinding.authority, 'requestBundle.binding.authority') !== canonicalize(authenticatedRequest.authority, 'requestBundle.request.authority') || canonicalize( authenticatedRehearsalBinding.payload, 'requestBundle.binding.payload', ) !== canonicalize( authenticatedRequest.payload.rehearsalBinding, 'requestBundle.request.rehearsalBinding', ) || authenticatedRehearsalBinding.payloadSha256 !== authenticatedRequest.payload.rehearsalBindingSha256) { fail('CROSS_FIELD_MISMATCH', 'requestBundle.authenticatedRehearsalBinding'); } return finalize({ schemaVersion: 1, kind: 'cloudly-legacy-deployment-settlement-request-bundle', authenticatedRehearsalBinding, authenticatedRequest, }, cloudlyLegacyDeploymentSettlementLimits.maximumAuthenticatedArtifactBytes * 2, 'requestBundle'); }; export const encodeCloudlyLegacyDeploymentSettlementRequestBundle = ( valueArg: unknown, ): Uint8Array => encodeNormalized( normalizeCloudlyLegacyDeploymentSettlementRequestBundle(valueArg), 'requestBundle', ); export const digestCloudlyLegacyDeploymentSettlementRequestBundle = ( valueArg: unknown, ): string => digestBytes(encodeCloudlyLegacyDeploymentSettlementRequestBundle(valueArg)); const executionAttemptIdentityKeys = [ 'schemaVersion', 'kind', 'attemptId', 'purpose', 'operationId', 'settlementId', 'executionAuthority', 'sourceAuthority', 'authenticatedPlanSha256', 'requestBundleSha256', 'scratchReceiptSha256', ] as const; const executionAttemptIdentitySeed = ( valueArg: Omit, ): unknown => ({ schemaVersion: valueArg.schemaVersion, kind: valueArg.kind, purpose: valueArg.purpose, operationId: valueArg.operationId, settlementId: valueArg.settlementId, executionAuthority: valueArg.executionAuthority, sourceAuthority: valueArg.sourceAuthority, authenticatedPlanSha256: valueArg.authenticatedPlanSha256, requestBundleSha256: valueArg.requestBundleSha256, scratchReceiptSha256: valueArg.scratchReceiptSha256, }); const createExecutionAttemptId = ( valueArg: Omit, ): string => `settlement-attempt-${digestBytes(encodeNormalized( executionAttemptIdentitySeed(valueArg), 'executionAttemptIdentity.seed', )).slice(0, 40)}`; const normalizeExecutionAttemptIdentityInternal = ( valueArg: unknown, pathArg: string, ): TCloudlyLegacyDeploymentSettlementExecutionAttemptIdentityV1 => { const value = readRecord(valueArg, pathArg); assertExactKeys(value, executionAttemptIdentityKeys, pathArg); if (value.schemaVersion !== 1 || value.kind !== 'cloudly-legacy-deployment-settlement-execution-attempt-identity') { fail('INVALID_VALUE', `${pathArg}.kind`); } const purpose = readLiteral( value.purpose, ['scratch-rehearsal', 'production'], `${pathArg}.purpose`, ); const operationId = readIdentifier(value.operationId, `${pathArg}.operationId`); const executionAuthority = normalizeAuthorityReferenceInternal( value.executionAuthority, `${pathArg}.executionAuthority`, ); const sourceAuthority = normalizeAuthorityReferenceInternal( value.sourceAuthority, `${pathArg}.sourceAuthority`, ); const usesSameAuthority = canonicalize(executionAuthority, `${pathArg}.executionAuthority`) === canonicalize(sourceAuthority, `${pathArg}.sourceAuthority`); if (executionAuthority.operationId !== operationId || sourceAuthority.operationId !== operationId || (purpose === 'scratch-rehearsal') !== usesSameAuthority) { fail('CROSS_FIELD_MISMATCH', `${pathArg}.executionAuthority`); } const scratchReceiptSha256 = value.scratchReceiptSha256 === null ? null : readSha256(value.scratchReceiptSha256, `${pathArg}.scratchReceiptSha256`); if ((purpose === 'production') !== (scratchReceiptSha256 !== null)) { fail('CROSS_FIELD_MISMATCH', `${pathArg}.scratchReceiptSha256`); } const identityWithoutId = { schemaVersion: 1 as const, kind: 'cloudly-legacy-deployment-settlement-execution-attempt-identity' as const, purpose, operationId, settlementId: readIdentifier(value.settlementId, `${pathArg}.settlementId`), executionAuthority, sourceAuthority, authenticatedPlanSha256: readSha256( value.authenticatedPlanSha256, `${pathArg}.authenticatedPlanSha256`, ), requestBundleSha256: readSha256( value.requestBundleSha256, `${pathArg}.requestBundleSha256`, ), scratchReceiptSha256, }; const attemptId = readIdentifier(value.attemptId, `${pathArg}.attemptId`); if (attemptId !== createExecutionAttemptId(identityWithoutId)) { fail('CROSS_FIELD_MISMATCH', `${pathArg}.attemptId`); } return { ...identityWithoutId, attemptId } as TCloudlyLegacyDeploymentSettlementExecutionAttemptIdentityV1; }; export function createCloudlyLegacyDeploymentSettlementExecutionAttemptIdentity( valueArg: Omit< TCloudlyLegacyDeploymentSettlementScratchExecutionAttemptIdentityV1, 'schemaVersion' | 'kind' | 'attemptId' >, ): Readonly; export function createCloudlyLegacyDeploymentSettlementExecutionAttemptIdentity( valueArg: Omit< TCloudlyLegacyDeploymentSettlementProductionExecutionAttemptIdentityV1, 'schemaVersion' | 'kind' | 'attemptId' >, ): Readonly; export function createCloudlyLegacyDeploymentSettlementExecutionAttemptIdentity( valueArg: Omit< ICloudlyLegacyDeploymentSettlementExecutionAttemptIdentityV1, 'schemaVersion' | 'kind' | 'attemptId' >, ): Readonly; export function createCloudlyLegacyDeploymentSettlementExecutionAttemptIdentity( valueArg: Omit< ICloudlyLegacyDeploymentSettlementExecutionAttemptIdentityV1, 'schemaVersion' | 'kind' | 'attemptId' >, ): Readonly { const seed = { schemaVersion: 1 as const, kind: 'cloudly-legacy-deployment-settlement-execution-attempt-identity' as const, purpose: valueArg.purpose, operationId: valueArg.operationId, settlementId: valueArg.settlementId, executionAuthority: valueArg.executionAuthority, sourceAuthority: valueArg.sourceAuthority, authenticatedPlanSha256: valueArg.authenticatedPlanSha256, requestBundleSha256: valueArg.requestBundleSha256, scratchReceiptSha256: valueArg.scratchReceiptSha256, }; return normalizeCloudlyLegacyDeploymentSettlementExecutionAttemptIdentity({ ...seed, attemptId: createExecutionAttemptId(seed), }); } export const normalizeCloudlyLegacyDeploymentSettlementExecutionAttemptIdentity = ( valueArg: unknown, ): Readonly => finalize( normalizeExecutionAttemptIdentityInternal(valueArg, 'executionAttemptIdentity'), cloudlyLegacyDeploymentSettlementLimits.maximumAuthorityBytes, 'executionAttemptIdentity', ); export const encodeCloudlyLegacyDeploymentSettlementExecutionAttemptIdentity = ( valueArg: unknown, ): Uint8Array => encodeNormalized( normalizeCloudlyLegacyDeploymentSettlementExecutionAttemptIdentity(valueArg), 'executionAttemptIdentity', ); export const digestCloudlyLegacyDeploymentSettlementExecutionAttemptIdentity = ( valueArg: unknown, ): string => digestBytes( encodeCloudlyLegacyDeploymentSettlementExecutionAttemptIdentity(valueArg), ); const normalizeExecutionAttemptObservationInternal = ( valueArg: unknown, pathArg: string, ): TCloudlyLegacyDeploymentSettlementExecutionAttemptObservationV1 => { const value = readRecord(valueArg, pathArg); const state = readLiteral(value.state, ['prepared', 'committed', 'aborted'], `${pathArg}.state`); assertExactKeys(value, [ 'schemaVersion', 'kind', 'identity', 'state', 'preparedAt', ...(state === 'committed' ? ['resolvedAt', 'receiptSchemaVersion', 'receiptSha256'] : []), ...(state === 'aborted' ? ['resolvedAt'] : []), ], pathArg); if (value.schemaVersion !== 1 || value.kind !== 'cloudly-legacy-deployment-settlement-execution-attempt-observation') { fail('INVALID_VALUE', `${pathArg}.kind`); } const identity = normalizeExecutionAttemptIdentityInternal(value.identity, `${pathArg}.identity`); const preparedAt = readInteger(value.preparedAt, `${pathArg}.preparedAt`, 1); if (state === 'prepared') { return { schemaVersion: 1, kind: 'cloudly-legacy-deployment-settlement-execution-attempt-observation', identity, state, preparedAt, }; } const resolvedAt = readInteger(value.resolvedAt, `${pathArg}.resolvedAt`, preparedAt); if (state === 'aborted') { return { schemaVersion: 1, kind: 'cloudly-legacy-deployment-settlement-execution-attempt-observation', identity, state, preparedAt, resolvedAt, }; } if (value.receiptSchemaVersion !== 1 && value.receiptSchemaVersion !== 2) { fail('INVALID_VALUE', `${pathArg}.receiptSchemaVersion`); } const receiptSchemaVersion = value.receiptSchemaVersion as 1 | 2; return { schemaVersion: 1, kind: 'cloudly-legacy-deployment-settlement-execution-attempt-observation', identity, state, preparedAt, resolvedAt, receiptSchemaVersion, receiptSha256: readSha256(value.receiptSha256, `${pathArg}.receiptSha256`), }; }; export const normalizeCloudlyLegacyDeploymentSettlementExecutionAttemptObservation = ( valueArg: unknown, ): Readonly => finalize( normalizeExecutionAttemptObservationInternal(valueArg, 'executionAttemptObservation'), cloudlyLegacyDeploymentSettlementLimits.maximumAuthorityBytes, 'executionAttemptObservation', ); export const encodeCloudlyLegacyDeploymentSettlementExecutionAttemptObservation = ( valueArg: unknown, ): Uint8Array => encodeNormalized( normalizeCloudlyLegacyDeploymentSettlementExecutionAttemptObservation(valueArg), 'executionAttemptObservation', ); export const digestCloudlyLegacyDeploymentSettlementExecutionAttemptObservation = ( valueArg: unknown, ): string => digestBytes( encodeCloudlyLegacyDeploymentSettlementExecutionAttemptObservation(valueArg), ); export interface ICloudlyLegacyDeploymentSettlementProductionExecutionAuthorizationPayloadV1 { schemaVersion: 1; kind: 'cloudly-legacy-deployment-settlement-production-execution-authorization'; authority: ICloudlyLegacyDeploymentSettlementAuthorityReferenceV1; sourceAuthority: ICloudlyLegacyDeploymentSettlementAuthorityReferenceV1; executionAttempt: TCloudlyLegacyDeploymentSettlementProductionExecutionAttemptIdentityV1; authenticatedPlanSha256: string; requestBundleSha256: string; scratchReceiptSha256: string; maintenanceImageDigest: `sha256:${string}`; operationId: string; settlementId: string; runId: string; rehearsalId: string; scratchServiceId: string; allocationId: string; allocationGeneration: number; allocationBindingSha256: string; allocationReceiptSha256: string; sourceImageDigest: `sha256:${string}`; targetImageDigest: `sha256:${string}`; requestedAt: number; approvedAt: number; } export interface ICloudlyLegacyDeploymentSettlementProductionExecutionAuthorizationV1 extends ICloudlyLegacyDeploymentSettlementProductionExecutionAuthorizationPayloadV1 { payloadSha256: string; mac: string; } export type TCloudlyLegacyDeploymentSettlementUnsignedProductionExecutionAuthorizationV1 = Omit; export interface ICloudlyLegacyDeploymentSettlementProductionReceiptPayloadV2 { schemaVersion: 2; kind: 'cloudly-legacy-deployment-settlement-production-receipt'; authority: ICloudlyLegacyDeploymentSettlementAuthorityReferenceV1; sourceAuthority: ICloudlyLegacyDeploymentSettlementAuthorityReferenceV1; executionAttempt: TCloudlyLegacyDeploymentSettlementProductionExecutionAttemptIdentityV1; productionAuthorization: ICloudlyLegacyDeploymentSettlementProductionExecutionAuthorizationV1; productionAuthorizationSha256: string; requestSha256: string; requestBundleSha256: string; scratchReceipt: ICloudlyLegacyDeploymentSettlementScratchReceiptV1; scratchReceiptSha256: string; stableOutcome: ICloudlyLegacyDeploymentSettlementStableOutcomeV1; stableOutcomeSha256: string; transactionCommitted: true; disposition: 'applied' | 'exact-replay' | 'no-op'; completedAt: number; } export interface ICloudlyLegacyDeploymentSettlementProductionReceiptV2 extends ICloudlyLegacyDeploymentSettlementProductionReceiptPayloadV2 { payloadSha256: string; mac: string; } export type TCloudlyLegacyDeploymentSettlementUnsignedProductionReceiptV2 = Omit; export type TCloudlyLegacyDeploymentSettlementProductionReceipt = | ICloudlyLegacyDeploymentSettlementProductionReceiptV1 | ICloudlyLegacyDeploymentSettlementProductionReceiptV2; const productionExecutionAuthorizationPayloadKeys = [ 'schemaVersion', 'kind', 'authority', 'sourceAuthority', 'executionAttempt', 'authenticatedPlanSha256', 'requestBundleSha256', 'scratchReceiptSha256', 'maintenanceImageDigest', 'operationId', 'settlementId', 'runId', 'rehearsalId', 'scratchServiceId', 'allocationId', 'allocationGeneration', 'allocationBindingSha256', 'allocationReceiptSha256', 'sourceImageDigest', 'targetImageDigest', 'requestedAt', 'approvedAt', ] as const; const unsignedProductionExecutionAuthorizationKeys = [ ...productionExecutionAuthorizationPayloadKeys, 'payloadSha256', ] as const; const productionExecutionAuthorizationKeys = [ ...unsignedProductionExecutionAuthorizationKeys, 'mac', ] as const; const productionExecutionAuthorizationPayload = ( valueArg: ICloudlyLegacyDeploymentSettlementProductionExecutionAuthorizationPayloadV1, ): unknown => Object.fromEntries(productionExecutionAuthorizationPayloadKeys.map((keyArg) => [ keyArg, valueArg[keyArg], ])); const normalizeProductionExecutionAuthorizationPayloadInternal = ( valueArg: unknown, pathArg: string, ): ICloudlyLegacyDeploymentSettlementProductionExecutionAuthorizationPayloadV1 => { const value = readRecord(valueArg, pathArg); assertExactKeys(value, productionExecutionAuthorizationPayloadKeys, pathArg); if (value.schemaVersion !== 1 || value.kind !== 'cloudly-legacy-deployment-settlement-production-execution-authorization') { fail('INVALID_VALUE', `${pathArg}.kind`); } const authority = normalizeAuthorityReferenceInternal(value.authority, `${pathArg}.authority`); const sourceAuthority = normalizeAuthorityReferenceInternal( value.sourceAuthority, `${pathArg}.sourceAuthority`, ); const executionAttempt = normalizeExecutionAttemptIdentityInternal( value.executionAttempt, `${pathArg}.executionAttempt`, ); const operationId = readIdentifier(value.operationId, `${pathArg}.operationId`); const settlementId = readIdentifier(value.settlementId, `${pathArg}.settlementId`); const authenticatedPlanSha256 = readSha256( value.authenticatedPlanSha256, `${pathArg}.authenticatedPlanSha256`, ); const requestBundleSha256 = readSha256( value.requestBundleSha256, `${pathArg}.requestBundleSha256`, ); const scratchReceiptSha256 = readSha256( value.scratchReceiptSha256, `${pathArg}.scratchReceiptSha256`, ); if (executionAttempt.purpose !== 'production' || executionAttempt.operationId !== operationId || executionAttempt.settlementId !== settlementId || authority.authorityId === sourceAuthority.authorityId || authority.keyId === sourceAuthority.keyId || canonicalize(authority, `${pathArg}.authority`) === canonicalize(sourceAuthority, `${pathArg}.sourceAuthority`) || canonicalize(executionAttempt.executionAuthority, `${pathArg}.attempt.executionAuthority`) !== canonicalize(authority, `${pathArg}.authority`) || canonicalize(executionAttempt.sourceAuthority, `${pathArg}.attempt.sourceAuthority`) !== canonicalize(sourceAuthority, `${pathArg}.sourceAuthority`) || executionAttempt.authenticatedPlanSha256 !== authenticatedPlanSha256 || executionAttempt.requestBundleSha256 !== requestBundleSha256 || executionAttempt.scratchReceiptSha256 !== scratchReceiptSha256) { fail('CROSS_FIELD_MISMATCH', `${pathArg}.executionAttempt`); } const requestedAt = readInteger(value.requestedAt, `${pathArg}.requestedAt`, 1); const approvedAt = readInteger(value.approvedAt, `${pathArg}.approvedAt`, requestedAt); return { schemaVersion: 1, kind: 'cloudly-legacy-deployment-settlement-production-execution-authorization', authority, sourceAuthority, executionAttempt: executionAttempt as TCloudlyLegacyDeploymentSettlementProductionExecutionAttemptIdentityV1, authenticatedPlanSha256, requestBundleSha256, scratchReceiptSha256, maintenanceImageDigest: readOciDigest( value.maintenanceImageDigest, `${pathArg}.maintenanceImageDigest`, ), operationId, settlementId, runId: readIdentifier(value.runId, `${pathArg}.runId`), rehearsalId: readIdentifier(value.rehearsalId, `${pathArg}.rehearsalId`), scratchServiceId: readIdentifier(value.scratchServiceId, `${pathArg}.scratchServiceId`), allocationId: readIdentifier(value.allocationId, `${pathArg}.allocationId`), allocationGeneration: readInteger( value.allocationGeneration, `${pathArg}.allocationGeneration`, 1, ), allocationBindingSha256: readSha256( value.allocationBindingSha256, `${pathArg}.allocationBindingSha256`, ), allocationReceiptSha256: readSha256( value.allocationReceiptSha256, `${pathArg}.allocationReceiptSha256`, ), sourceImageDigest: readOciDigest(value.sourceImageDigest, `${pathArg}.sourceImageDigest`), targetImageDigest: readOciDigest(value.targetImageDigest, `${pathArg}.targetImageDigest`), requestedAt, approvedAt, }; }; const normalizeUnsignedProductionExecutionAuthorizationInternal = ( valueArg: unknown, pathArg: string, ): TCloudlyLegacyDeploymentSettlementUnsignedProductionExecutionAuthorizationV1 => { const value = readRecord(valueArg, pathArg); assertExactKeys(value, unsignedProductionExecutionAuthorizationKeys, pathArg); const payloadInput = Object.fromEntries(productionExecutionAuthorizationPayloadKeys.map( (keyArg) => [keyArg, value[keyArg]], )); const payload = normalizeProductionExecutionAuthorizationPayloadInternal( payloadInput, `${pathArg}.payload`, ); const payloadSha256 = readSha256(value.payloadSha256, `${pathArg}.payloadSha256`); if (payloadSha256 !== digestBytes(encodeNormalized( productionExecutionAuthorizationPayload(payload), `${pathArg}.payload`, ))) { fail('CROSS_FIELD_MISMATCH', `${pathArg}.payloadSha256`); } return { ...payload, payloadSha256 }; }; export const normalizeCloudlyLegacyDeploymentSettlementProductionExecutionAuthorization = ( valueArg: unknown, ): Readonly => { const value = readRecord(valueArg, 'productionExecutionAuthorization'); assertExactKeys(value, productionExecutionAuthorizationKeys, 'productionExecutionAuthorization'); const unsignedInput = Object.fromEntries(unsignedProductionExecutionAuthorizationKeys.map( (keyArg) => [keyArg, value[keyArg]], )); return finalize({ ...normalizeUnsignedProductionExecutionAuthorizationInternal( unsignedInput, 'productionExecutionAuthorization.unsigned', ), mac: readMac(value.mac, 'productionExecutionAuthorization.mac'), }, cloudlyLegacyDeploymentSettlementLimits.maximumReceiptBytes, 'productionExecutionAuthorization'); }; export const digestCloudlyLegacyDeploymentSettlementProductionExecutionAuthorizationPayload = ( valueArg: unknown, ): string => digestBytes(encodeNormalized( productionExecutionAuthorizationPayload( normalizeProductionExecutionAuthorizationPayloadInternal( valueArg, 'productionExecutionAuthorizationPayload', ), ), 'productionExecutionAuthorizationPayload', )); export const encodeCloudlyLegacyDeploymentSettlementProductionExecutionAuthorization = ( valueArg: unknown, ): Uint8Array => encodeNormalized( normalizeCloudlyLegacyDeploymentSettlementProductionExecutionAuthorization(valueArg), 'productionExecutionAuthorization', ); export const digestCloudlyLegacyDeploymentSettlementProductionExecutionAuthorization = ( valueArg: unknown, ): string => digestBytes( encodeCloudlyLegacyDeploymentSettlementProductionExecutionAuthorization(valueArg), ); export const encodeCloudlyLegacyDeploymentSettlementProductionExecutionAuthorizationHmacInput = ( valueArg: unknown, ): Uint8Array => frame( cloudlyLegacyDeploymentSettlementDomains.productionExecutionAuthorizationHmac, encodeNormalized( finalize( normalizeUnsignedProductionExecutionAuthorizationInternal( valueArg, 'unsignedProductionExecutionAuthorization', ), cloudlyLegacyDeploymentSettlementLimits.maximumReceiptBytes, 'unsignedProductionExecutionAuthorization', ), 'productionExecutionAuthorization.authenticated', ), ); export const normalizeCloudlyLegacyDeploymentSettlementRequestBundleForAuthority = async ( bundleArg: unknown, authenticatedPlanArg: unknown, metadataArg: unknown, verifierArg: TCloudlyLegacyDeploymentSettlementHmacVerifier, ): Promise> => { const metadata = normalizeCloudlyLegacyDeploymentSettlementAuthorityMetadata(metadataArg); const plan = await normalizeAuthenticatedCloudlyLegacyDeploymentSettlementPlanForAuthority( authenticatedPlanArg, metadata, verifierArg, ); const bundle = normalizeCloudlyLegacyDeploymentSettlementRequestBundle(bundleArg); await normalizeAuthenticatedCloudlyLegacyDeploymentSettlementRehearsalBindingForAuthority( bundle.authenticatedRehearsalBinding, metadata, verifierArg, ); await normalizeAuthenticatedCloudlyLegacyDeploymentSettlementProductionRequestForAuthority( bundle.authenticatedRequest, metadata, verifierArg, ); if (canonicalize(plan.payload, 'requestBundle.plan') !== canonicalize(bundle.authenticatedRequest.payload.plan, 'requestBundle.request.plan') || plan.payloadSha256 !== bundle.authenticatedRequest.payload.planSha256) { fail('CROSS_FIELD_MISMATCH', 'requestBundle.authenticatedRequest.plan'); } return bundle; }; const assertProductionAuthorizationMetadata = ( authorizationArg: ICloudlyLegacyDeploymentSettlementProductionExecutionAuthorizationV1, productionMetadataArg: ICloudlyLegacyDeploymentSettlementFencedProductionAuthorityMetadataV1, sourceMetadataArg: ICloudlyLegacyDeploymentSettlementFencedSourceAuthorityMetadataV1, ): void => { assertAuthorityReferenceMatchesMetadata( authorizationArg.authority, productionMetadataArg, 'productionExecutionAuthorization.authority', ); assertAuthorityReferenceMatchesMetadata( authorizationArg.sourceAuthority, sourceMetadataArg, 'productionExecutionAuthorization.sourceAuthority', ); if (canonicalize(productionMetadataArg.sourceAuthority, 'productionMetadata.sourceAuthority') !== canonicalize(authorizationArg.sourceAuthority, 'authorization.sourceAuthority') || productionMetadataArg.sourceAuthenticatedPlanSha256 !== authorizationArg.authenticatedPlanSha256 || productionMetadataArg.sourceRequestBundleSha256 !== authorizationArg.requestBundleSha256 || productionMetadataArg.scratchReceiptSha256 !== authorizationArg.scratchReceiptSha256 || authorizationArg.operationId !== productionMetadataArg.operationId || authorizationArg.operationId !== sourceMetadataArg.operationId || authorizationArg.settlementId !== productionMetadataArg.settlementId || authorizationArg.settlementId !== sourceMetadataArg.settlementId || authorizationArg.runId !== productionMetadataArg.runId || authorizationArg.runId !== sourceMetadataArg.runId || authorizationArg.rehearsalId !== productionMetadataArg.rehearsalId || authorizationArg.rehearsalId !== sourceMetadataArg.rehearsalId || authorizationArg.scratchServiceId !== productionMetadataArg.scratchServiceId || authorizationArg.scratchServiceId !== sourceMetadataArg.scratchServiceId || authorizationArg.allocationId !== productionMetadataArg.allocationId || authorizationArg.allocationId !== sourceMetadataArg.allocationId || authorizationArg.allocationGeneration !== productionMetadataArg.allocationGeneration || authorizationArg.allocationGeneration !== sourceMetadataArg.allocationGeneration || authorizationArg.allocationBindingSha256 !== productionMetadataArg.allocationBindingSha256 || authorizationArg.allocationBindingSha256 !== sourceMetadataArg.allocationBindingSha256 || authorizationArg.allocationReceiptSha256 !== productionMetadataArg.allocationReceiptSha256 || authorizationArg.allocationReceiptSha256 !== sourceMetadataArg.allocationReceiptSha256 || authorizationArg.maintenanceImageDigest !== productionMetadataArg.maintenanceImageDigest || authorizationArg.sourceImageDigest !== productionMetadataArg.sourceImageDigest || authorizationArg.sourceImageDigest !== sourceMetadataArg.sourceImageDigest || authorizationArg.targetImageDigest !== productionMetadataArg.targetImageDigest || authorizationArg.targetImageDigest !== sourceMetadataArg.targetImageDigest) { fail('CROSS_FIELD_MISMATCH', 'productionExecutionAuthorization.authorityMetadata'); } assertAuthorityTimestamp( authorizationArg.requestedAt, productionMetadataArg, 'productionExecutionAuthorization.requestedAt', ); assertAuthorityTimestamp( authorizationArg.approvedAt, productionMetadataArg, 'productionExecutionAuthorization.approvedAt', ); }; const assertProductionAuthorizationArtifacts = ( authorizationArg: ICloudlyLegacyDeploymentSettlementProductionExecutionAuthorizationV1, productionMetadataArg: ICloudlyLegacyDeploymentSettlementFencedProductionAuthorityMetadataV1, sourceMetadataArg: ICloudlyLegacyDeploymentSettlementFencedSourceAuthorityMetadataV1, authenticatedPlanArg: IAuthenticatedCloudlyLegacyDeploymentSettlementPlanV1, requestBundleArg: ICloudlyLegacyDeploymentSettlementRequestBundleV1, scratchReceiptArg: ICloudlyLegacyDeploymentSettlementScratchReceiptV1, ): void => { if (authorizationArg.authenticatedPlanSha256 !== digestAuthenticatedCloudlyLegacyDeploymentSettlementPlan(authenticatedPlanArg) || authorizationArg.requestBundleSha256 !== digestCloudlyLegacyDeploymentSettlementRequestBundle(requestBundleArg) || authorizationArg.scratchReceiptSha256 !== digestCloudlyLegacyDeploymentSettlementScratchReceipt(scratchReceiptArg) || productionMetadataArg.issuedAt <= scratchReceiptArg.completedAt || authorizationArg.requestedAt <= scratchReceiptArg.completedAt || authorizationArg.requestedAt < productionMetadataArg.issuedAt || authorizationArg.approvedAt < authorizationArg.requestedAt) { fail('CROSS_FIELD_MISMATCH', 'productionExecutionAuthorization.sourceProof'); } assertProductionAuthorizationMetadata( authorizationArg, productionMetadataArg, sourceMetadataArg, ); }; export const normalizeCloudlyLegacyDeploymentSettlementProductionExecutionAuthorizationForAuthorities = async ( authorizationArg: unknown, productionMetadataArg: unknown, sourceMetadataArg: unknown, authenticatedPlanArg: unknown, requestBundleArg: unknown, scratchReceiptArg: unknown, verifierArg: TCloudlyLegacyDeploymentSettlementHmacVerifier, ): Promise> => { const { productionMetadata, sourceMetadata, } = normalizeProductionAuthorityMetadataPair( productionMetadataArg, sourceMetadataArg, ); const plan = await normalizeAuthenticatedCloudlyLegacyDeploymentSettlementPlanForAuthority( authenticatedPlanArg, sourceMetadata, verifierArg, ); const requestBundle = await normalizeCloudlyLegacyDeploymentSettlementRequestBundleForAuthority( requestBundleArg, plan, sourceMetadata, verifierArg, ); const scratchReceipt = await normalizeCloudlyLegacyDeploymentSettlementScratchReceiptForAuthority( scratchReceiptArg, sourceMetadata, requestBundle.authenticatedRequest, verifierArg, ); const authorization = normalizeCloudlyLegacyDeploymentSettlementProductionExecutionAuthorization(authorizationArg); assertProductionAuthorizationArtifacts( authorization, productionMetadata, sourceMetadata, plan, requestBundle, scratchReceipt, ); await requireConsumerVerifiedHmac( authorization.authority, cloudlyLegacyDeploymentSettlementDomains.productionExecutionAuthorizationHmac, encodeCloudlyLegacyDeploymentSettlementProductionExecutionAuthorizationHmacInput( withoutArtifactMac(authorization), ), authorization.mac, verifierArg, 'productionExecutionAuthorization.mac', ); return authorization; }; const productionReceiptV2PayloadKeys = [ 'schemaVersion', 'kind', 'authority', 'sourceAuthority', 'executionAttempt', 'productionAuthorization', 'productionAuthorizationSha256', 'requestSha256', 'requestBundleSha256', 'scratchReceipt', 'scratchReceiptSha256', 'stableOutcome', 'stableOutcomeSha256', 'transactionCommitted', 'disposition', 'completedAt', ] as const; const unsignedProductionReceiptV2Keys = [...productionReceiptV2PayloadKeys, 'payloadSha256'] as const; const productionReceiptV2Keys = [...unsignedProductionReceiptV2Keys, 'mac'] as const; const productionReceiptV2Payload = ( valueArg: ICloudlyLegacyDeploymentSettlementProductionReceiptPayloadV2, ): unknown => Object.fromEntries(productionReceiptV2PayloadKeys.map((keyArg) => [ keyArg, valueArg[keyArg], ])); const normalizeProductionReceiptV2PayloadInternal = ( valueArg: unknown, pathArg: string, ): ICloudlyLegacyDeploymentSettlementProductionReceiptPayloadV2 => { const value = readRecord(valueArg, pathArg); assertExactKeys(value, productionReceiptV2PayloadKeys, pathArg); if (value.schemaVersion !== 2 || value.kind !== 'cloudly-legacy-deployment-settlement-production-receipt' || value.transactionCommitted !== true) { fail('INVALID_VALUE', `${pathArg}.kind`); } const authority = normalizeAuthorityReferenceInternal(value.authority, `${pathArg}.authority`); const sourceAuthority = normalizeAuthorityReferenceInternal( value.sourceAuthority, `${pathArg}.sourceAuthority`, ); const executionAttempt = normalizeExecutionAttemptIdentityInternal( value.executionAttempt, `${pathArg}.executionAttempt`, ); const productionAuthorization = normalizeCloudlyLegacyDeploymentSettlementProductionExecutionAuthorization( value.productionAuthorization, ); const productionAuthorizationSha256 = readSha256( value.productionAuthorizationSha256, `${pathArg}.productionAuthorizationSha256`, ); const requestBundleSha256 = readSha256( value.requestBundleSha256, `${pathArg}.requestBundleSha256`, ); const scratchReceipt = normalizeScratchReceiptInternal( value.scratchReceipt, `${pathArg}.scratchReceipt`, ); const scratchReceiptSha256 = readSha256( value.scratchReceiptSha256, `${pathArg}.scratchReceiptSha256`, ); const stableOutcome = normalizeStableOutcomeInternal( value.stableOutcome, `${pathArg}.stableOutcome`, ); const stableOutcomeSha256 = readSha256( value.stableOutcomeSha256, `${pathArg}.stableOutcomeSha256`, ); const requestSha256 = readSha256(value.requestSha256, `${pathArg}.requestSha256`); const disposition = readLiteral( value.disposition, ['applied', 'exact-replay', 'no-op'], `${pathArg}.disposition`, ); const dispositionMatchesScratch = disposition === scratchReceipt.disposition || (scratchReceipt.disposition === 'applied' && disposition === 'exact-replay'); if (canonicalize(authority, `${pathArg}.authority`) !== canonicalize(productionAuthorization.authority, `${pathArg}.authorization.authority`) || canonicalize(sourceAuthority, `${pathArg}.sourceAuthority`) !== canonicalize(productionAuthorization.sourceAuthority, `${pathArg}.authorization.sourceAuthority`) || canonicalize(executionAttempt, `${pathArg}.executionAttempt`) !== canonicalize(productionAuthorization.executionAttempt, `${pathArg}.authorization.attempt`) || productionAuthorizationSha256 !== digestCloudlyLegacyDeploymentSettlementProductionExecutionAuthorization( productionAuthorization, ) || requestBundleSha256 !== productionAuthorization.requestBundleSha256 || scratchReceiptSha256 !== productionAuthorization.scratchReceiptSha256 || scratchReceiptSha256 !== digestCloudlyLegacyDeploymentSettlementScratchReceipt(scratchReceipt) || canonicalize(sourceAuthority, `${pathArg}.sourceAuthority`) !== canonicalize(scratchReceipt.authority, `${pathArg}.scratchReceipt.authority`) || requestSha256 !== scratchReceipt.requestSha256 || !dispositionMatchesScratch || canonicalize(stableOutcome, `${pathArg}.stableOutcome`) !== canonicalize(scratchReceipt.stableOutcome, `${pathArg}.scratchReceipt.stableOutcome`) || stableOutcomeSha256 !== scratchReceipt.stableOutcomeSha256 || stableOutcomeSha256 !== digestCloudlyLegacyDeploymentSettlementStableOutcome(stableOutcome)) { fail('CROSS_FIELD_MISMATCH', `${pathArg}.productionAuthorization`); } return { schemaVersion: 2, kind: 'cloudly-legacy-deployment-settlement-production-receipt', authority, sourceAuthority, executionAttempt: executionAttempt as TCloudlyLegacyDeploymentSettlementProductionExecutionAttemptIdentityV1, productionAuthorization, productionAuthorizationSha256, requestSha256, requestBundleSha256, scratchReceipt, scratchReceiptSha256, stableOutcome, stableOutcomeSha256, transactionCommitted: true, disposition, completedAt: readInteger( value.completedAt, `${pathArg}.completedAt`, productionAuthorization.approvedAt, ), }; }; const normalizeUnsignedProductionReceiptV2Internal = ( valueArg: unknown, pathArg: string, ): TCloudlyLegacyDeploymentSettlementUnsignedProductionReceiptV2 => { const value = readRecord(valueArg, pathArg); assertExactKeys(value, unsignedProductionReceiptV2Keys, pathArg); const payloadInput = Object.fromEntries(productionReceiptV2PayloadKeys.map( (keyArg) => [keyArg, value[keyArg]], )); const payload = normalizeProductionReceiptV2PayloadInternal(payloadInput, `${pathArg}.payload`); const payloadSha256 = readSha256(value.payloadSha256, `${pathArg}.payloadSha256`); if (payloadSha256 !== digestBytes(encodeNormalized( productionReceiptV2Payload(payload), `${pathArg}.payload`, ))) { fail('CROSS_FIELD_MISMATCH', `${pathArg}.payloadSha256`); } return { ...payload, payloadSha256 }; }; export const digestCloudlyLegacyDeploymentSettlementProductionReceiptPayloadV2 = ( valueArg: unknown, ): string => digestBytes(encodeNormalized( productionReceiptV2Payload( normalizeProductionReceiptV2PayloadInternal(valueArg, 'productionReceiptPayloadV2'), ), 'productionReceiptPayloadV2', )); export const normalizeCloudlyLegacyDeploymentSettlementProductionReceiptV2 = ( valueArg: unknown, ): Readonly => { const value = readRecord(valueArg, 'productionReceiptV2'); assertExactKeys(value, productionReceiptV2Keys, 'productionReceiptV2'); const unsignedInput = Object.fromEntries(unsignedProductionReceiptV2Keys.map( (keyArg) => [keyArg, value[keyArg]], )); return finalize({ ...normalizeUnsignedProductionReceiptV2Internal(unsignedInput, 'productionReceiptV2.unsigned'), mac: readMac(value.mac, 'productionReceiptV2.mac'), }, cloudlyLegacyDeploymentSettlementLimits.maximumReceiptBytes * 3, 'productionReceiptV2'); }; export const normalizeCloudlyLegacyDeploymentSettlementProductionReceiptAnyVersion = ( valueArg: unknown, ): Readonly => { const value = readRecord(valueArg, 'productionReceipt'); return value.schemaVersion === 2 ? normalizeCloudlyLegacyDeploymentSettlementProductionReceiptV2(value) : normalizeCloudlyLegacyDeploymentSettlementProductionReceipt(value); }; export const encodeCloudlyLegacyDeploymentSettlementProductionReceiptV2 = ( valueArg: unknown, ): Uint8Array => encodeNormalized( normalizeCloudlyLegacyDeploymentSettlementProductionReceiptV2(valueArg), 'productionReceiptV2', ); export const digestCloudlyLegacyDeploymentSettlementProductionReceiptV2 = ( valueArg: unknown, ): string => digestBytes(encodeCloudlyLegacyDeploymentSettlementProductionReceiptV2(valueArg)); export const encodeCloudlyLegacyDeploymentSettlementProductionReceiptV2HmacInput = ( valueArg: unknown, ): Uint8Array => frame( cloudlyLegacyDeploymentSettlementDomains.productionReceiptV2Hmac, encodeNormalized( finalize( normalizeUnsignedProductionReceiptV2Internal(valueArg, 'unsignedProductionReceiptV2'), cloudlyLegacyDeploymentSettlementLimits.maximumReceiptBytes * 3, 'unsignedProductionReceiptV2', ), 'productionReceiptV2.authenticated', ), ); export const normalizeCloudlyLegacyDeploymentSettlementProductionReceiptV2ForAuthorities = async ( receiptArg: unknown, productionMetadataArg: unknown, sourceMetadataArg: unknown, authenticatedPlanArg: unknown, requestBundleArg: unknown, verifierArg: TCloudlyLegacyDeploymentSettlementHmacVerifier, ): Promise> => { const { productionMetadata, sourceMetadata, } = normalizeProductionAuthorityMetadataPair( productionMetadataArg, sourceMetadataArg, ); const receipt = normalizeCloudlyLegacyDeploymentSettlementProductionReceiptV2(receiptArg); const requestBundle = normalizeCloudlyLegacyDeploymentSettlementRequestBundle(requestBundleArg); await normalizeCloudlyLegacyDeploymentSettlementProductionExecutionAuthorizationForAuthorities( receipt.productionAuthorization, productionMetadata, sourceMetadata, authenticatedPlanArg, requestBundle, receipt.scratchReceipt, verifierArg, ); await normalizeCloudlyLegacyDeploymentSettlementScratchReceiptForAuthority( receipt.scratchReceipt, sourceMetadata, requestBundle.authenticatedRequest, verifierArg, ); assertAuthorityReferenceMatchesMetadata( receipt.authority, productionMetadata, 'productionReceiptV2.authority', ); assertAuthorityTimestamp(receipt.completedAt, productionMetadata, 'productionReceiptV2.completedAt'); await requireConsumerVerifiedHmac( receipt.authority, cloudlyLegacyDeploymentSettlementDomains.productionReceiptV2Hmac, encodeCloudlyLegacyDeploymentSettlementProductionReceiptV2HmacInput( withoutArtifactMac(receipt), ), receipt.mac, verifierArg, 'productionReceiptV2.mac', ); return receipt; }; export type TCloudlyLegacyDeploymentSettlementAuthorityStatus = 'active' | 'expired'; export type TCloudlyLegacyDeploymentSettlementResolutionMode = | 'committed-schema1' | 'committed-schema2' | 'aborted-prepared' | 'observed-aborted' | 'absent-tombstone' | 'legacy-no-op'; export type TCloudlyLegacyDeploymentSettlementCommittedReceipt = | ICloudlyLegacyDeploymentSettlementScratchReceiptV1 | ICloudlyLegacyDeploymentSettlementProductionReceiptV2; type TCloudlyLegacyDeploymentSettlementCommittedObservationV1< TAttempt extends TCloudlyLegacyDeploymentSettlementExecutionAttemptIdentityV1, TReceiptSchemaVersion extends 1 | 2, > = Omit< ICloudlyLegacyDeploymentSettlementExecutionAttemptCommittedV1, 'identity' | 'receiptSchemaVersion' > & { identity: TAttempt; receiptSchemaVersion: TReceiptSchemaVersion; }; interface ICloudlyLegacyDeploymentSettlementResolutionBundleBaseV1 { schemaVersion: 1; kind: 'cloudly-legacy-deployment-settlement-resolution-bundle'; executionAttempt: TCloudlyLegacyDeploymentSettlementExecutionAttemptIdentityV1; observedAt: number; sourceAuthorityStatus: TCloudlyLegacyDeploymentSettlementAuthorityStatus; executionAuthorityStatus: TCloudlyLegacyDeploymentSettlementAuthorityStatus; } export interface ICloudlyLegacyDeploymentSettlementCommittedScratchSchema1ResolutionBundleV1 extends ICloudlyLegacyDeploymentSettlementResolutionBundleBaseV1 { outcome: 'committed'; mode: 'committed-schema1'; executionAttempt: TCloudlyLegacyDeploymentSettlementScratchExecutionAttemptIdentityV1; attemptObservation: TCloudlyLegacyDeploymentSettlementCommittedObservationV1< TCloudlyLegacyDeploymentSettlementScratchExecutionAttemptIdentityV1, 1 >; originalReceipt: ICloudlyLegacyDeploymentSettlementScratchReceiptV1; originalReceiptSha256: string; } export interface ICloudlyLegacyDeploymentSettlementCommittedSchema2ResolutionBundleV1 extends ICloudlyLegacyDeploymentSettlementResolutionBundleBaseV1 { outcome: 'committed'; mode: 'committed-schema2'; executionAttempt: TCloudlyLegacyDeploymentSettlementProductionExecutionAttemptIdentityV1; attemptObservation: TCloudlyLegacyDeploymentSettlementCommittedObservationV1< TCloudlyLegacyDeploymentSettlementProductionExecutionAttemptIdentityV1, 2 >; originalReceipt: ICloudlyLegacyDeploymentSettlementProductionReceiptV2; originalReceiptSha256: string; } export type TCloudlyLegacyDeploymentSettlementCommittedResolutionBundleV1 = | ICloudlyLegacyDeploymentSettlementCommittedScratchSchema1ResolutionBundleV1 | ICloudlyLegacyDeploymentSettlementCommittedSchema2ResolutionBundleV1; export interface ICloudlyLegacyDeploymentSettlementAbortedPreparedResolutionBundleV1 extends ICloudlyLegacyDeploymentSettlementResolutionBundleBaseV1 { outcome: 'unapplied'; mode: 'aborted-prepared'; attemptObservation: ICloudlyLegacyDeploymentSettlementExecutionAttemptAbortedV1; } export interface ICloudlyLegacyDeploymentSettlementObservedAbortedResolutionBundleV1 extends ICloudlyLegacyDeploymentSettlementResolutionBundleBaseV1 { outcome: 'unapplied'; mode: 'observed-aborted'; attemptObservation: ICloudlyLegacyDeploymentSettlementExecutionAttemptAbortedV1; } export type TCloudlyLegacyDeploymentSettlementAbortedResolutionBundleV1 = | ICloudlyLegacyDeploymentSettlementAbortedPreparedResolutionBundleV1 | ICloudlyLegacyDeploymentSettlementObservedAbortedResolutionBundleV1; export interface ICloudlyLegacyDeploymentSettlementAbsentTombstoneResolutionBundleV1 extends ICloudlyLegacyDeploymentSettlementResolutionBundleBaseV1 { outcome: 'unapplied'; mode: 'absent-tombstone'; attemptObservation: ICloudlyLegacyDeploymentSettlementExecutionAttemptAbortedV1; } export interface ICloudlyLegacyDeploymentSettlementLegacyNoOpResolutionBundleV1 extends ICloudlyLegacyDeploymentSettlementResolutionBundleBaseV1 { outcome: 'unapplied'; mode: 'legacy-no-op'; executionAttempt: TCloudlyLegacyDeploymentSettlementScratchExecutionAttemptIdentityV1; attemptObservation: null; } export type TCloudlyLegacyDeploymentSettlementResolutionBundleV1 = | ICloudlyLegacyDeploymentSettlementCommittedScratchSchema1ResolutionBundleV1 | ICloudlyLegacyDeploymentSettlementCommittedSchema2ResolutionBundleV1 | ICloudlyLegacyDeploymentSettlementAbortedPreparedResolutionBundleV1 | ICloudlyLegacyDeploymentSettlementObservedAbortedResolutionBundleV1 | ICloudlyLegacyDeploymentSettlementAbsentTombstoneResolutionBundleV1 | ICloudlyLegacyDeploymentSettlementLegacyNoOpResolutionBundleV1; const normalizeCommittedResolutionReceipt = ( valueArg: unknown, pathArg: string, ): Readonly => { const value = readRecord(valueArg, pathArg); if (value.kind === 'cloudly-legacy-deployment-settlement-scratch-receipt') { return normalizeCloudlyLegacyDeploymentSettlementScratchReceipt(value); } if (value.kind !== 'cloudly-legacy-deployment-settlement-production-receipt') { fail('INVALID_VALUE', `${pathArg}.kind`); } if (value.schemaVersion !== 2) { fail('INVALID_VALUE', `${pathArg}.schemaVersion`); } return normalizeCloudlyLegacyDeploymentSettlementProductionReceiptV2(value); }; /** Structural only; this function does not authenticate receipt MACs. */ export const normalizeCloudlyLegacyDeploymentSettlementResolutionBundle = ( valueArg: unknown, ): Readonly => { const value = readRecord(valueArg, 'resolutionBundle'); const outcome = readLiteral(value.outcome, ['committed', 'unapplied'], 'resolutionBundle.outcome'); const mode = readLiteral(value.mode, [ 'committed-schema1', 'committed-schema2', 'aborted-prepared', 'observed-aborted', 'absent-tombstone', 'legacy-no-op', ], 'resolutionBundle.mode'); const committed = outcome === 'committed'; assertExactKeys(value, [ 'schemaVersion', 'kind', 'executionAttempt', 'observedAt', 'sourceAuthorityStatus', 'executionAuthorityStatus', 'outcome', 'mode', 'attemptObservation', ...(committed ? ['originalReceipt', 'originalReceiptSha256'] : []), ], 'resolutionBundle'); if (value.schemaVersion !== 1 || value.kind !== 'cloudly-legacy-deployment-settlement-resolution-bundle') { fail('INVALID_VALUE', 'resolutionBundle.kind'); } const executionAttempt = normalizeExecutionAttemptIdentityInternal( value.executionAttempt, 'resolutionBundle.executionAttempt', ); const observedAt = readInteger(value.observedAt, 'resolutionBundle.observedAt', 1); const sourceAuthorityStatus = readLiteral( value.sourceAuthorityStatus, ['active', 'expired'], 'resolutionBundle.sourceAuthorityStatus', ); const executionAuthorityStatus = readLiteral( value.executionAuthorityStatus, ['active', 'expired'], 'resolutionBundle.executionAuthorityStatus', ); if (canonicalize(executionAttempt.sourceAuthority, 'resolutionBundle.sourceAuthority') === canonicalize(executionAttempt.executionAuthority, 'resolutionBundle.executionAuthority') && sourceAuthorityStatus !== executionAuthorityStatus) { fail('CROSS_FIELD_MISMATCH', 'resolutionBundle.executionAuthorityStatus'); } if (committed) { if (mode !== 'committed-schema1' && mode !== 'committed-schema2') { fail('CROSS_FIELD_MISMATCH', 'resolutionBundle.mode'); } const attemptObservation = normalizeExecutionAttemptObservationInternal( value.attemptObservation, 'resolutionBundle.attemptObservation', ); if (attemptObservation.state !== 'committed') { fail('CROSS_FIELD_MISMATCH', 'resolutionBundle.attemptObservation'); } const committedObservation = attemptObservation as ICloudlyLegacyDeploymentSettlementExecutionAttemptCommittedV1; if (canonicalize(committedObservation.identity, 'resolutionBundle.observation.identity') !== canonicalize(executionAttempt, 'resolutionBundle.executionAttempt')) { fail('CROSS_FIELD_MISMATCH', 'resolutionBundle.attemptObservation'); } const originalReceipt = normalizeCommittedResolutionReceipt( value.originalReceipt, 'resolutionBundle.originalReceipt', ); const receiptSchemaVersion = originalReceipt.schemaVersion; const originalReceiptSha256 = readSha256( value.originalReceiptSha256, 'resolutionBundle.originalReceiptSha256', ); const expectedReceiptSha256 = originalReceipt.kind === 'cloudly-legacy-deployment-settlement-scratch-receipt' ? digestCloudlyLegacyDeploymentSettlementScratchReceipt(originalReceipt) : originalReceipt.schemaVersion === 2 ? digestCloudlyLegacyDeploymentSettlementProductionReceiptV2(originalReceipt) : digestCloudlyLegacyDeploymentSettlementProductionReceipt(originalReceipt); const receiptExecutionAuthority = originalReceipt.authority; const receiptSourceAuthority = originalReceipt.schemaVersion === 2 ? originalReceipt.sourceAuthority : originalReceipt.authority; if ((mode === 'committed-schema1') !== (receiptSchemaVersion === 1) || committedObservation.receiptSchemaVersion !== receiptSchemaVersion || committedObservation.receiptSha256 !== originalReceiptSha256 || originalReceiptSha256 !== expectedReceiptSha256 || committedObservation.resolvedAt !== originalReceipt.completedAt || observedAt < committedObservation.resolvedAt || canonicalize(receiptExecutionAuthority, 'resolutionBundle.receipt.executionAuthority') !== canonicalize(executionAttempt.executionAuthority, 'resolutionBundle.executionAuthority') || canonicalize(receiptSourceAuthority, 'resolutionBundle.receipt.sourceAuthority') !== canonicalize(executionAttempt.sourceAuthority, 'resolutionBundle.sourceAuthority') || (originalReceipt.schemaVersion === 2 && canonicalize(originalReceipt.executionAttempt, 'resolutionBundle.receipt.executionAttempt') !== canonicalize(executionAttempt, 'resolutionBundle.executionAttempt')) || (executionAttempt.purpose === 'scratch-rehearsal') !== (originalReceipt.kind === 'cloudly-legacy-deployment-settlement-scratch-receipt')) { fail('CROSS_FIELD_MISMATCH', 'resolutionBundle.originalReceipt'); } let result: TCloudlyLegacyDeploymentSettlementCommittedResolutionBundleV1; if (mode === 'committed-schema1' && originalReceipt.kind === 'cloudly-legacy-deployment-settlement-scratch-receipt') { const scratchAttempt = executionAttempt as TCloudlyLegacyDeploymentSettlementScratchExecutionAttemptIdentityV1; result = { schemaVersion: 1, kind: 'cloudly-legacy-deployment-settlement-resolution-bundle', executionAttempt: scratchAttempt, observedAt, sourceAuthorityStatus, executionAuthorityStatus, outcome, mode, attemptObservation: { ...committedObservation, identity: scratchAttempt, receiptSchemaVersion: 1, }, originalReceipt, originalReceiptSha256, }; } else { const productionAttempt = executionAttempt as TCloudlyLegacyDeploymentSettlementProductionExecutionAttemptIdentityV1; result = { schemaVersion: 1, kind: 'cloudly-legacy-deployment-settlement-resolution-bundle', executionAttempt: productionAttempt, observedAt, sourceAuthorityStatus, executionAuthorityStatus, outcome, mode: 'committed-schema2', attemptObservation: { ...committedObservation, identity: productionAttempt, receiptSchemaVersion: 2, }, originalReceipt: originalReceipt as ICloudlyLegacyDeploymentSettlementProductionReceiptV2, originalReceiptSha256, }; } return finalize( result, cloudlyLegacyDeploymentSettlementLimits.maximumReceiptBytes * 4, 'resolutionBundle', ); } if (mode === 'committed-schema1' || mode === 'committed-schema2') { fail('CROSS_FIELD_MISMATCH', 'resolutionBundle.mode'); } if (mode === 'aborted-prepared' || mode === 'observed-aborted' || mode === 'absent-tombstone') { const attemptObservation = normalizeExecutionAttemptObservationInternal( value.attemptObservation, 'resolutionBundle.attemptObservation', ); if (attemptObservation.state !== 'aborted') { fail('CROSS_FIELD_MISMATCH', 'resolutionBundle.attemptObservation'); } const abortedObservation = attemptObservation as ICloudlyLegacyDeploymentSettlementExecutionAttemptAbortedV1; if (canonicalize(abortedObservation.identity, 'resolutionBundle.observation.identity') !== canonicalize(executionAttempt, 'resolutionBundle.executionAttempt') || observedAt < abortedObservation.resolvedAt) { fail('CROSS_FIELD_MISMATCH', 'resolutionBundle.attemptObservation'); } if (mode === 'absent-tombstone') { const result: ICloudlyLegacyDeploymentSettlementAbsentTombstoneResolutionBundleV1 = { schemaVersion: 1, kind: 'cloudly-legacy-deployment-settlement-resolution-bundle', executionAttempt, observedAt, sourceAuthorityStatus, executionAuthorityStatus, outcome, mode, attemptObservation: abortedObservation, }; return finalize( result, cloudlyLegacyDeploymentSettlementLimits.maximumReceiptBytes, 'resolutionBundle', ); } const result = mode === 'aborted-prepared' ? { schemaVersion: 1 as const, kind: 'cloudly-legacy-deployment-settlement-resolution-bundle' as const, executionAttempt, observedAt, sourceAuthorityStatus, executionAuthorityStatus, outcome, mode, attemptObservation: abortedObservation, } satisfies ICloudlyLegacyDeploymentSettlementAbortedPreparedResolutionBundleV1 : { schemaVersion: 1 as const, kind: 'cloudly-legacy-deployment-settlement-resolution-bundle' as const, executionAttempt, observedAt, sourceAuthorityStatus, executionAuthorityStatus, outcome, mode, attemptObservation: abortedObservation, } satisfies ICloudlyLegacyDeploymentSettlementObservedAbortedResolutionBundleV1; return finalize( result, cloudlyLegacyDeploymentSettlementLimits.maximumReceiptBytes, 'resolutionBundle', ); } if (value.attemptObservation !== null) { fail('CROSS_FIELD_MISMATCH', 'resolutionBundle.attemptObservation'); } if (executionAttempt.purpose !== 'scratch-rehearsal') { fail('CROSS_FIELD_MISMATCH', 'resolutionBundle.executionAttempt'); } const scratchExecutionAttempt = executionAttempt as TCloudlyLegacyDeploymentSettlementScratchExecutionAttemptIdentityV1; const result: ICloudlyLegacyDeploymentSettlementLegacyNoOpResolutionBundleV1 = { schemaVersion: 1, kind: 'cloudly-legacy-deployment-settlement-resolution-bundle', executionAttempt: scratchExecutionAttempt, observedAt, sourceAuthorityStatus, executionAuthorityStatus, outcome, mode: 'legacy-no-op', attemptObservation: null, }; return finalize( result, cloudlyLegacyDeploymentSettlementLimits.maximumReceiptBytes, 'resolutionBundle', ); }; export const encodeCloudlyLegacyDeploymentSettlementResolutionBundle = ( valueArg: unknown, ): Uint8Array => encodeNormalized( normalizeCloudlyLegacyDeploymentSettlementResolutionBundle(valueArg), 'resolutionBundle', ); export const digestCloudlyLegacyDeploymentSettlementResolutionBundle = ( valueArg: unknown, ): string => digestBytes(encodeCloudlyLegacyDeploymentSettlementResolutionBundle(valueArg)); /** Recovery attestation only; this is neither a receipt nor an execution authorization. */ export interface IAuthenticatedCloudlyLegacyDeploymentSettlementResolutionV1 { schemaVersion: 1; kind: 'authenticated-cloudly-legacy-deployment-settlement-resolution'; authority: ICloudlyLegacyDeploymentSettlementAuthorityReferenceV1; payload: TCloudlyLegacyDeploymentSettlementResolutionBundleV1; payloadSha256: string; mac: string; } export type TUnsignedAuthenticatedCloudlyLegacyDeploymentSettlementResolutionV1 = Omit< IAuthenticatedCloudlyLegacyDeploymentSettlementResolutionV1, 'mac' >; const unsignedAuthenticatedResolutionKeys = [ 'schemaVersion', 'kind', 'authority', 'payload', 'payloadSha256', ] as const; const authenticatedResolutionKeys = [...unsignedAuthenticatedResolutionKeys, 'mac'] as const; const normalizeUnsignedAuthenticatedResolutionInternal = ( valueArg: unknown, pathArg: string, ): TUnsignedAuthenticatedCloudlyLegacyDeploymentSettlementResolutionV1 => { const value = readRecord(valueArg, pathArg); assertExactKeys(value, unsignedAuthenticatedResolutionKeys, pathArg); if (value.schemaVersion !== 1 || value.kind !== 'authenticated-cloudly-legacy-deployment-settlement-resolution') { fail('INVALID_VALUE', `${pathArg}.kind`); } const authority = normalizeAuthorityReferenceInternal(value.authority, `${pathArg}.authority`); const payload = normalizeCloudlyLegacyDeploymentSettlementResolutionBundle(value.payload); const payloadSha256 = readSha256(value.payloadSha256, `${pathArg}.payloadSha256`); if (canonicalize(authority, `${pathArg}.authority`) !== canonicalize(payload.executionAttempt.executionAuthority, `${pathArg}.payload.authority`) || payloadSha256 !== digestCloudlyLegacyDeploymentSettlementResolutionBundle(payload)) { fail('CROSS_FIELD_MISMATCH', `${pathArg}.payload`); } return { schemaVersion: 1, kind: 'authenticated-cloudly-legacy-deployment-settlement-resolution', authority, payload, payloadSha256, }; }; /** Structural only; this function does not authenticate the recovery-attestation MAC. */ export const normalizeCloudlyLegacyDeploymentSettlementAuthenticatedResolutionStructure = ( valueArg: unknown, ): Readonly => { const value = readRecord(valueArg, 'authenticatedResolution'); assertExactKeys(value, authenticatedResolutionKeys, 'authenticatedResolution'); return finalize({ ...normalizeUnsignedAuthenticatedResolutionInternal( Object.fromEntries(unsignedAuthenticatedResolutionKeys.map((keyArg) => [ keyArg, value[keyArg], ])), 'authenticatedResolution.unsigned', ), mac: readMac(value.mac, 'authenticatedResolution.mac'), }, cloudlyLegacyDeploymentSettlementLimits.maximumReceiptBytes * 5, 'authenticatedResolution'); }; export const encodeAuthenticatedCloudlyLegacyDeploymentSettlementResolution = ( valueArg: unknown, ): Uint8Array => encodeNormalized( normalizeCloudlyLegacyDeploymentSettlementAuthenticatedResolutionStructure(valueArg), 'authenticatedResolution', ); export const digestAuthenticatedCloudlyLegacyDeploymentSettlementResolution = ( valueArg: unknown, ): string => digestBytes(encodeAuthenticatedCloudlyLegacyDeploymentSettlementResolution(valueArg)); export const encodeCloudlyLegacyDeploymentSettlementResolutionHmacInput = ( valueArg: unknown, ): Uint8Array => frame( cloudlyLegacyDeploymentSettlementDomains.resolutionHmac, encodeNormalized( finalize( normalizeUnsignedAuthenticatedResolutionInternal( valueArg, 'unsignedAuthenticatedResolution', ), cloudlyLegacyDeploymentSettlementLimits.maximumReceiptBytes * 5, 'unsignedAuthenticatedResolution', ), 'authenticatedResolution.authenticated', ), ); const normalizeExecutionAttemptAuthorityMetadata = ( attemptArg: ICloudlyLegacyDeploymentSettlementExecutionAttemptIdentityV1, sourceMetadataArg: unknown, executionMetadataArg: unknown, ): { sourceMetadata: Readonly; executionMetadata: Readonly; splitProductionAuthority: boolean; } => { const sourceMetadata = normalizeFencedSourceAuthorityMetadata( sourceMetadataArg, 'executionAttempt.sourceAuthorityMetadata', ); const executionMetadata = normalizeCloudlyLegacyDeploymentSettlementAuthorityMetadata( executionMetadataArg, ); assertAuthorityReferenceMatchesMetadata( attemptArg.sourceAuthority, sourceMetadata, 'executionAttempt.sourceAuthority', ); assertAuthorityReferenceMatchesMetadata( attemptArg.executionAuthority, executionMetadata, 'executionAttempt.executionAuthority', ); const splitProductionAuthority = canonicalize( attemptArg.sourceAuthority, 'executionAttempt.sourceAuthority', ) !== canonicalize(attemptArg.executionAuthority, 'executionAttempt.executionAuthority'); if (attemptArg.purpose === 'scratch-rehearsal') { if (splitProductionAuthority) { fail('CROSS_FIELD_MISMATCH', 'executionAttempt.executionAuthority'); } normalizeFencedSourceAuthorityMetadata( executionMetadata, 'executionAttempt.executionAuthorityMetadata', ); } else { if (!splitProductionAuthority) { fail('CROSS_FIELD_MISMATCH', 'executionAttempt.executionAuthority'); } const productionMetadata = normalizeProductionAuthorityMetadataPair( executionMetadata, sourceMetadata, ).productionMetadata; if (productionMetadata.sourceAuthenticatedPlanSha256 !== attemptArg.authenticatedPlanSha256 || productionMetadata.sourceRequestBundleSha256 !== attemptArg.requestBundleSha256 || productionMetadata.scratchReceiptSha256 !== attemptArg.scratchReceiptSha256) { fail('CROSS_FIELD_MISMATCH', 'executionAttempt.productionAuthorityMetadata'); } } return { sourceMetadata, executionMetadata, splitProductionAuthority }; }; const authorityStatusAt = ( observedAtArg: number, metadataArg: TCloudlyLegacyDeploymentSettlementAuthorityMetadataV1, pathArg: string, ): TCloudlyLegacyDeploymentSettlementAuthorityStatus => { if (observedAtArg < metadataArg.issuedAt) { fail('CROSS_FIELD_MISMATCH', pathArg); } return observedAtArg < metadataArg.expiresAt ? 'active' : 'expired'; }; const normalizeExecutionAttemptProofArtifacts = async (argsArg: { executionAttempt: ICloudlyLegacyDeploymentSettlementExecutionAttemptIdentityV1; sourceMetadata: unknown; executionMetadata: unknown; authenticatedPlan: unknown; requestBundle: unknown; scratchReceipt: unknown | null; productionAuthorization: unknown | null; requireProductionAuthorization: boolean; verifier: TCloudlyLegacyDeploymentSettlementHmacVerifier; }): Promise<{ sourceMetadata: Readonly; executionMetadata: Readonly; authenticatedPlan: Readonly; requestBundle: Readonly; scratchReceipt: Readonly | null; productionAuthorization: Readonly | null; splitProductionAuthority: boolean; }> => { const metadata = normalizeExecutionAttemptAuthorityMetadata( argsArg.executionAttempt, argsArg.sourceMetadata, argsArg.executionMetadata, ); const authenticatedPlan = await normalizeAuthenticatedCloudlyLegacyDeploymentSettlementPlanForAuthority( argsArg.authenticatedPlan, metadata.sourceMetadata, argsArg.verifier, ); const requestBundle = await normalizeCloudlyLegacyDeploymentSettlementRequestBundleForAuthority( argsArg.requestBundle, authenticatedPlan, metadata.sourceMetadata, argsArg.verifier, ); let scratchReceipt: Readonly | null = null; let productionAuthorization: Readonly | null = null; if (argsArg.executionAttempt.purpose === 'production') { if (argsArg.scratchReceipt === null) { fail('INVALID_SCHEMA', 'executionAttempt.scratchReceipt'); } scratchReceipt = await normalizeCloudlyLegacyDeploymentSettlementScratchReceiptForAuthority( argsArg.scratchReceipt, metadata.sourceMetadata, requestBundle.authenticatedRequest, argsArg.verifier, ); if (metadata.splitProductionAuthority) { if (argsArg.productionAuthorization === null) { if (argsArg.requireProductionAuthorization) { fail('INVALID_SCHEMA', 'executionAttempt.productionAuthorization'); } } else { productionAuthorization = await normalizeCloudlyLegacyDeploymentSettlementProductionExecutionAuthorizationForAuthorities( argsArg.productionAuthorization, metadata.executionMetadata, metadata.sourceMetadata, authenticatedPlan, requestBundle, scratchReceipt, argsArg.verifier, ); } } else if (argsArg.productionAuthorization !== null) { fail('INVALID_SCHEMA', 'executionAttempt.productionAuthorization'); } } else if (argsArg.scratchReceipt !== null || argsArg.productionAuthorization !== null) { fail('INVALID_SCHEMA', 'executionAttempt.sourceProof'); } const expectedScratchReceiptSha256 = scratchReceipt ? digestCloudlyLegacyDeploymentSettlementScratchReceipt(scratchReceipt) : null; if (argsArg.executionAttempt.authenticatedPlanSha256 !== digestAuthenticatedCloudlyLegacyDeploymentSettlementPlan(authenticatedPlan) || argsArg.executionAttempt.requestBundleSha256 !== digestCloudlyLegacyDeploymentSettlementRequestBundle(requestBundle) || argsArg.executionAttempt.scratchReceiptSha256 !== expectedScratchReceiptSha256) { fail('CROSS_FIELD_MISMATCH', 'executionAttempt.sourceProof'); } return { ...metadata, authenticatedPlan, requestBundle, scratchReceipt, productionAuthorization, }; }; const normalizeAuthenticatedApplyResultForExecutionAuthority = async ( resultArg: unknown, executionMetadataArg: unknown, requestArg: unknown, productionAuthorizationArg: ICloudlyLegacyDeploymentSettlementProductionExecutionAuthorizationV1, verifierArg: TCloudlyLegacyDeploymentSettlementHmacVerifier, ): Promise> => { const executionMetadata = normalizeCloudlyLegacyDeploymentSettlementAuthorityMetadata( executionMetadataArg, ); const request = normalizeCloudlyLegacyDeploymentSettlementAuthenticatedProductionRequestStructure( requestArg, ); const result = normalizeCloudlyLegacyDeploymentSettlementAuthenticatedApplyResultStructure(resultArg); assertAuthorityReferenceMatchesMetadata(result.authority, executionMetadata, 'applyResult.authority'); assertSummaryMatchesProductionRequest(result.payload, request.payload, 'applyResult.payload'); const resultAt = result.payload.status === 'completed' ? result.payload.completedAt : result.payload.rejectedAt; const resultAtPath = result.payload.status === 'completed' ? 'applyResult.payload.completedAt' : 'applyResult.payload.rejectedAt'; if (canonicalize(result.authority, 'applyResult.authority') !== canonicalize(productionAuthorizationArg.authority, 'productionAuthorization.authority') || resultAt < request.payload.requestedAt || resultAt < productionAuthorizationArg.approvedAt) { fail('CROSS_FIELD_MISMATCH', resultAtPath); } assertAuthorityTimestamp(resultAt, executionMetadata, resultAtPath); await requireConsumerVerifiedHmac( result.authority, cloudlyLegacyDeploymentSettlementDomains.applyResultHmac, encodeCloudlyLegacyDeploymentSettlementApplyResultHmacInput(withoutArtifactMac(result)), result.mac, verifierArg, 'applyResult.mac', ); return result; }; const normalizeAuthenticatedCheckResultForExecutionAuthority = async ( resultArg: unknown, executionMetadataArg: unknown, requestArg: unknown, productionAuthorizationArg: ICloudlyLegacyDeploymentSettlementProductionExecutionAuthorizationV1, verifierArg: TCloudlyLegacyDeploymentSettlementHmacVerifier, ): Promise> => { const executionMetadata = normalizeCloudlyLegacyDeploymentSettlementAuthorityMetadata( executionMetadataArg, ); const request = normalizeCloudlyLegacyDeploymentSettlementAuthenticatedProductionRequestStructure( requestArg, ); const result = normalizeCloudlyLegacyDeploymentSettlementAuthenticatedCheckResultStructure(resultArg); assertAuthorityReferenceMatchesMetadata(result.authority, executionMetadata, 'checkResult.authority'); assertSummaryMatchesProductionRequest(result.payload, request.payload, 'checkResult.payload'); if (canonicalize(result.authority, 'checkResult.authority') !== canonicalize(productionAuthorizationArg.authority, 'productionAuthorization.authority') || result.payload.checkedAt < request.payload.requestedAt || result.payload.checkedAt < productionAuthorizationArg.approvedAt) { fail('CROSS_FIELD_MISMATCH', 'checkResult.payload.checkedAt'); } assertAuthorityTimestamp(result.payload.checkedAt, executionMetadata, 'checkResult.checkedAt'); await requireConsumerVerifiedHmac( result.authority, cloudlyLegacyDeploymentSettlementDomains.checkResultHmac, encodeCloudlyLegacyDeploymentSettlementCheckResultHmacInput(withoutArtifactMac(result)), result.mac, verifierArg, 'checkResult.mac', ); return result; }; /** Artifact/status binding only; trust the authenticated recovery attestation instead. */ export const normalizeCloudlyLegacyDeploymentSettlementResolutionBundleForAuthorities = async ( bundleArg: unknown, sourceMetadataArg: unknown, executionMetadataArg: unknown, authenticatedPlanArg: unknown, requestBundleArg: unknown, scratchReceiptArg: unknown | null, productionAuthorizationArg: unknown | null, verifierArg: TCloudlyLegacyDeploymentSettlementHmacVerifier, ): Promise> => { const bundle = normalizeCloudlyLegacyDeploymentSettlementResolutionBundle(bundleArg); const artifacts = await normalizeExecutionAttemptProofArtifacts({ executionAttempt: bundle.executionAttempt, sourceMetadata: sourceMetadataArg, executionMetadata: executionMetadataArg, authenticatedPlan: authenticatedPlanArg, requestBundle: requestBundleArg, scratchReceipt: scratchReceiptArg, productionAuthorization: productionAuthorizationArg, requireProductionAuthorization: true, verifier: verifierArg, }); if (bundle.sourceAuthorityStatus !== authorityStatusAt( bundle.observedAt, artifacts.sourceMetadata, 'resolutionBundle.sourceAuthorityStatus', )) { fail('CROSS_FIELD_MISMATCH', 'resolutionBundle.sourceAuthorityStatus'); } if (bundle.executionAuthorityStatus !== authorityStatusAt( bundle.observedAt, artifacts.executionMetadata, 'resolutionBundle.executionAuthorityStatus', )) { fail('CROSS_FIELD_MISMATCH', 'resolutionBundle.executionAuthorityStatus'); } if (bundle.executionAttempt.purpose === 'production') { const productionAuthorization = artifacts.productionAuthorization ?? fail('CROSS_FIELD_MISMATCH', 'resolutionBundle.productionAuthorization'); const attemptObservation = bundle.attemptObservation ?? fail('CROSS_FIELD_MISMATCH', 'resolutionBundle.attemptObservation'); if (attemptObservation.preparedAt < productionAuthorization.approvedAt || attemptObservation.resolvedAt < productionAuthorization.approvedAt || bundle.observedAt < productionAuthorization.approvedAt) { fail('CROSS_FIELD_MISMATCH', 'resolutionBundle.attemptObservation.preparedAt'); } } if (bundle.outcome === 'committed') { const receipt = bundle.originalReceipt; if (receipt.kind === 'cloudly-legacy-deployment-settlement-scratch-receipt') { await normalizeCloudlyLegacyDeploymentSettlementScratchReceiptForAuthority( receipt, artifacts.sourceMetadata, artifacts.requestBundle.authenticatedRequest, verifierArg, ); } else if (receipt.schemaVersion === 2) { if (!artifacts.splitProductionAuthority || !artifacts.productionAuthorization) { fail('CROSS_FIELD_MISMATCH', 'resolutionBundle.originalReceipt.authority'); } await normalizeCloudlyLegacyDeploymentSettlementProductionReceiptV2ForAuthorities( receipt, artifacts.executionMetadata, artifacts.sourceMetadata, artifacts.authenticatedPlan, artifacts.requestBundle, verifierArg, ); if (canonicalize( receipt.productionAuthorization, 'resolutionBundle.originalReceipt.productionAuthorization', ) !== canonicalize( artifacts.productionAuthorization, 'resolutionBundle.productionAuthorization', )) { fail('CROSS_FIELD_MISMATCH', 'resolutionBundle.originalReceipt.productionAuthorization'); } } else { if (artifacts.splitProductionAuthority) { fail('CROSS_FIELD_MISMATCH', 'resolutionBundle.originalReceipt.authority'); } await normalizeCloudlyLegacyDeploymentSettlementProductionReceiptForAuthority( receipt, artifacts.sourceMetadata, artifacts.requestBundle.authenticatedRequest, verifierArg, ); } if (receipt.kind === 'cloudly-legacy-deployment-settlement-production-receipt' && artifacts.scratchReceipt && digestCloudlyLegacyDeploymentSettlementScratchReceipt(receipt.scratchReceipt) !== digestCloudlyLegacyDeploymentSettlementScratchReceipt(artifacts.scratchReceipt)) { fail('CROSS_FIELD_MISMATCH', 'resolutionBundle.originalReceipt.scratchReceipt'); } } return bundle; }; export const normalizeAuthenticatedCloudlyLegacyDeploymentSettlementResolutionForAuthorities = async ( attestationArg: unknown, sourceMetadataArg: unknown, executionMetadataArg: unknown, authenticatedPlanArg: unknown, requestBundleArg: unknown, scratchReceiptArg: unknown | null, productionAuthorizationArg: unknown | null, verifierArg: TCloudlyLegacyDeploymentSettlementHmacVerifier, ): Promise> => { const attestation = normalizeCloudlyLegacyDeploymentSettlementAuthenticatedResolutionStructure(attestationArg); const executionMetadata = normalizeCloudlyLegacyDeploymentSettlementAuthorityMetadata( executionMetadataArg, ); assertAuthorityReferenceMatchesMetadata( attestation.authority, executionMetadata, 'authenticatedResolution.authority', ); await requireConsumerVerifiedHmac( attestation.authority, cloudlyLegacyDeploymentSettlementDomains.resolutionHmac, encodeCloudlyLegacyDeploymentSettlementResolutionHmacInput( withoutArtifactMac(attestation), ), attestation.mac, verifierArg, 'authenticatedResolution.mac', ); const payload = await normalizeCloudlyLegacyDeploymentSettlementResolutionBundleForAuthorities( attestation.payload, sourceMetadataArg, executionMetadata, authenticatedPlanArg, requestBundleArg, scratchReceiptArg, productionAuthorizationArg, verifierArg, ); if (canonicalize(attestation.payload, 'authenticatedResolution.payload') !== canonicalize(payload, 'authenticatedResolution.verifiedPayload')) { fail('CROSS_FIELD_MISMATCH', 'authenticatedResolution.payload'); } return attestation; }; export type TCloudlyLegacyDeploymentSettlementCompletedApplyResultV1 = Extract< TCloudlyLegacyDeploymentSettlementApplyResultV1, { status: 'completed' } >; export type TCloudlyLegacyDeploymentSettlementRejectedApplyResultV1 = Extract< TCloudlyLegacyDeploymentSettlementApplyResultV1, { status: 'rejected' } >; export type TAuthenticatedCloudlyLegacyDeploymentSettlementCompletedApplyResultV1 = Omit< IAuthenticatedCloudlyLegacyDeploymentSettlementApplyResultV1, 'payload' > & { payload: TCloudlyLegacyDeploymentSettlementCompletedApplyResultV1; }; export type TAuthenticatedCloudlyLegacyDeploymentSettlementRejectedApplyResultV1 = Omit< IAuthenticatedCloudlyLegacyDeploymentSettlementApplyResultV1, 'payload' > & { payload: TCloudlyLegacyDeploymentSettlementRejectedApplyResultV1; }; interface ICloudlyLegacyDeploymentSettlementScratchExecutionBundleBaseV1 { schemaVersion: 1; kind: 'cloudly-legacy-deployment-settlement-execution-bundle'; purpose: 'scratch-rehearsal'; executionAttempt: TCloudlyLegacyDeploymentSettlementScratchExecutionAttemptIdentityV1; } export interface ICloudlyLegacyDeploymentSettlementCompletedScratchExecutionBundleV1 extends ICloudlyLegacyDeploymentSettlementScratchExecutionBundleBaseV1 { authenticatedResult: TAuthenticatedCloudlyLegacyDeploymentSettlementCompletedApplyResultV1; receipt: ICloudlyLegacyDeploymentSettlementScratchReceiptV1; } export interface ICloudlyLegacyDeploymentSettlementRejectedScratchExecutionBundleV1 extends ICloudlyLegacyDeploymentSettlementScratchExecutionBundleBaseV1 { authenticatedResult: TAuthenticatedCloudlyLegacyDeploymentSettlementRejectedApplyResultV1; receipt?: never; } export type TCloudlyLegacyDeploymentSettlementScratchExecutionBundleV1 = | ICloudlyLegacyDeploymentSettlementCompletedScratchExecutionBundleV1 | ICloudlyLegacyDeploymentSettlementRejectedScratchExecutionBundleV1; interface ICloudlyLegacyDeploymentSettlementProductionExecutionBundleBaseV2 { schemaVersion: 2; kind: 'cloudly-legacy-deployment-settlement-execution-bundle'; purpose: 'production'; executionAttempt: TCloudlyLegacyDeploymentSettlementProductionExecutionAttemptIdentityV1; } export interface ICloudlyLegacyDeploymentSettlementCompletedProductionExecutionBundleV2 extends ICloudlyLegacyDeploymentSettlementProductionExecutionBundleBaseV2 { authenticatedResult: TAuthenticatedCloudlyLegacyDeploymentSettlementCompletedApplyResultV1; receipt: ICloudlyLegacyDeploymentSettlementProductionReceiptV2; } export interface ICloudlyLegacyDeploymentSettlementRejectedProductionExecutionBundleV2 extends ICloudlyLegacyDeploymentSettlementProductionExecutionBundleBaseV2 { authenticatedResult: TAuthenticatedCloudlyLegacyDeploymentSettlementRejectedApplyResultV1; receipt?: never; } export type TCloudlyLegacyDeploymentSettlementProductionExecutionBundleV2 = | ICloudlyLegacyDeploymentSettlementCompletedProductionExecutionBundleV2 | ICloudlyLegacyDeploymentSettlementRejectedProductionExecutionBundleV2; const normalizeSettlementExecutionBundleCommon = ( valueArg: unknown, pathArg: string, purposeArg: TCloudlyLegacyDeploymentSettlementExecutionPurpose, ): { value: Record; executionAttempt: ICloudlyLegacyDeploymentSettlementExecutionAttemptIdentityV1; authenticatedResult: IAuthenticatedCloudlyLegacyDeploymentSettlementApplyResultV1; hasReceipt: boolean; } => { const value = readRecord(valueArg, pathArg); const hasReceipt = Object.hasOwn(value, 'receipt'); assertExactKeys(value, [ 'schemaVersion', 'kind', 'purpose', 'executionAttempt', 'authenticatedResult', ...(hasReceipt ? ['receipt'] : []), ], pathArg); if (value.kind !== 'cloudly-legacy-deployment-settlement-execution-bundle' || value.purpose !== purposeArg) { fail('INVALID_VALUE', `${pathArg}.kind`); } const executionAttempt = normalizeExecutionAttemptIdentityInternal( value.executionAttempt, `${pathArg}.executionAttempt`, ); const authenticatedResult = normalizeCloudlyLegacyDeploymentSettlementAuthenticatedApplyResultStructure( value.authenticatedResult, ); if (executionAttempt.purpose !== purposeArg || canonicalize(authenticatedResult.authority, `${pathArg}.result.authority`) !== canonicalize(executionAttempt.executionAuthority, `${pathArg}.attempt.authority`) || (authenticatedResult.payload.status === 'completed') !== hasReceipt) { fail('CROSS_FIELD_MISMATCH', `${pathArg}.authenticatedResult`); } return { value, executionAttempt, authenticatedResult, hasReceipt }; }; /** Structural only; this function does not authenticate result or receipt MACs. */ export const normalizeCloudlyLegacyDeploymentSettlementScratchExecutionBundle = ( valueArg: unknown, ): Readonly => { const normalized = normalizeSettlementExecutionBundleCommon( valueArg, 'scratchExecutionBundle', 'scratch-rehearsal', ); if (normalized.value.schemaVersion !== 1) { fail('INVALID_VALUE', 'scratchExecutionBundle.schemaVersion'); } const receipt = normalized.hasReceipt ? normalizeCloudlyLegacyDeploymentSettlementScratchReceipt(normalized.value.receipt) : undefined; if (receipt && (canonicalize(receipt.authority, 'scratchExecutionBundle.receipt.authority') !== canonicalize( normalized.executionAttempt.executionAuthority, 'scratchExecutionBundle.attempt.authority', ) || normalized.authenticatedResult.payload.status !== 'completed' || normalized.authenticatedResult.payload.requestSha256 !== receipt.requestSha256 || (normalized.authenticatedResult.payload.disposition !== receipt.disposition && !(receipt.disposition === 'applied' && normalized.authenticatedResult.payload.disposition === 'exact-replay')))) { fail('CROSS_FIELD_MISMATCH', 'scratchExecutionBundle.receipt'); } const executionAttempt = normalized.executionAttempt as TCloudlyLegacyDeploymentSettlementScratchExecutionAttemptIdentityV1; const result: TCloudlyLegacyDeploymentSettlementScratchExecutionBundleV1 = receipt ? { schemaVersion: 1, kind: 'cloudly-legacy-deployment-settlement-execution-bundle', purpose: 'scratch-rehearsal', executionAttempt, authenticatedResult: normalized.authenticatedResult as TAuthenticatedCloudlyLegacyDeploymentSettlementCompletedApplyResultV1, receipt, } : { schemaVersion: 1, kind: 'cloudly-legacy-deployment-settlement-execution-bundle', purpose: 'scratch-rehearsal', executionAttempt, authenticatedResult: normalized.authenticatedResult as TAuthenticatedCloudlyLegacyDeploymentSettlementRejectedApplyResultV1, }; return finalize( result, cloudlyLegacyDeploymentSettlementLimits.maximumReceiptBytes * 2, 'scratchExecutionBundle', ); }; /** Structural only; this function does not authenticate result or receipt MACs. */ export const normalizeCloudlyLegacyDeploymentSettlementProductionExecutionBundleV2 = ( valueArg: unknown, ): Readonly => { const normalized = normalizeSettlementExecutionBundleCommon( valueArg, 'productionExecutionBundleV2', 'production', ); if (normalized.value.schemaVersion !== 2) { fail('INVALID_VALUE', 'productionExecutionBundleV2.schemaVersion'); } const receipt = normalized.hasReceipt ? normalizeCloudlyLegacyDeploymentSettlementProductionReceiptV2(normalized.value.receipt) : undefined; if (receipt && (canonicalize(receipt.executionAttempt, 'productionExecutionBundleV2.receipt.attempt') !== canonicalize( normalized.executionAttempt, 'productionExecutionBundleV2.executionAttempt', ) || normalized.authenticatedResult.payload.status !== 'completed' || normalized.authenticatedResult.payload.requestSha256 !== receipt.requestSha256 || (normalized.authenticatedResult.payload.disposition !== receipt.disposition && !(receipt.disposition === 'applied' && normalized.authenticatedResult.payload.disposition === 'exact-replay')))) { fail('CROSS_FIELD_MISMATCH', 'productionExecutionBundleV2.receipt'); } const executionAttempt = normalized.executionAttempt as TCloudlyLegacyDeploymentSettlementProductionExecutionAttemptIdentityV1; const result: TCloudlyLegacyDeploymentSettlementProductionExecutionBundleV2 = receipt ? { schemaVersion: 2, kind: 'cloudly-legacy-deployment-settlement-execution-bundle', purpose: 'production', executionAttempt, authenticatedResult: normalized.authenticatedResult as TAuthenticatedCloudlyLegacyDeploymentSettlementCompletedApplyResultV1, receipt, } : { schemaVersion: 2, kind: 'cloudly-legacy-deployment-settlement-execution-bundle', purpose: 'production', executionAttempt, authenticatedResult: normalized.authenticatedResult as TAuthenticatedCloudlyLegacyDeploymentSettlementRejectedApplyResultV1, }; return finalize( result, cloudlyLegacyDeploymentSettlementLimits.maximumReceiptBytes * 4, 'productionExecutionBundleV2', ); }; export const encodeCloudlyLegacyDeploymentSettlementScratchExecutionBundle = ( valueArg: unknown, ): Uint8Array => encodeNormalized( normalizeCloudlyLegacyDeploymentSettlementScratchExecutionBundle(valueArg), 'scratchExecutionBundle', ); export const encodeCloudlyLegacyDeploymentSettlementProductionExecutionBundleV2 = ( valueArg: unknown, ): Uint8Array => encodeNormalized( normalizeCloudlyLegacyDeploymentSettlementProductionExecutionBundleV2(valueArg), 'productionExecutionBundleV2', ); export const normalizeCloudlyLegacyDeploymentSettlementScratchExecutionBundleForAuthority = async ( bundleArg: unknown, sourceMetadataArg: unknown, authenticatedPlanArg: unknown, requestBundleArg: unknown, verifierArg: TCloudlyLegacyDeploymentSettlementHmacVerifier, ): Promise> => { const bundle = normalizeCloudlyLegacyDeploymentSettlementScratchExecutionBundle(bundleArg); const artifacts = await normalizeExecutionAttemptProofArtifacts({ executionAttempt: bundle.executionAttempt, sourceMetadata: sourceMetadataArg, executionMetadata: sourceMetadataArg, authenticatedPlan: authenticatedPlanArg, requestBundle: requestBundleArg, scratchReceipt: null, productionAuthorization: null, requireProductionAuthorization: false, verifier: verifierArg, }); await normalizeAuthenticatedCloudlyLegacyDeploymentSettlementApplyResultForAuthority( bundle.authenticatedResult, artifacts.sourceMetadata, artifacts.requestBundle.authenticatedRequest, verifierArg, ); if (bundle.receipt) { await normalizeCloudlyLegacyDeploymentSettlementScratchReceiptForAuthority( bundle.receipt, artifacts.sourceMetadata, artifacts.requestBundle.authenticatedRequest, verifierArg, ); } return bundle; }; export const normalizeCloudlyLegacyDeploymentSettlementProductionExecutionBundleV2ForAuthorities = async ( bundleArg: unknown, productionAuthorizationArg: unknown, productionMetadataArg: unknown, sourceMetadataArg: unknown, authenticatedPlanArg: unknown, requestBundleArg: unknown, scratchReceiptArg: unknown, verifierArg: TCloudlyLegacyDeploymentSettlementHmacVerifier, ): Promise> => { const bundle = normalizeCloudlyLegacyDeploymentSettlementProductionExecutionBundleV2(bundleArg); const artifacts = await normalizeExecutionAttemptProofArtifacts({ executionAttempt: bundle.executionAttempt, sourceMetadata: sourceMetadataArg, executionMetadata: productionMetadataArg, authenticatedPlan: authenticatedPlanArg, requestBundle: requestBundleArg, scratchReceipt: scratchReceiptArg, productionAuthorization: productionAuthorizationArg, requireProductionAuthorization: true, verifier: verifierArg, }); const productionAuthorization = artifacts.productionAuthorization ?? fail('CROSS_FIELD_MISMATCH', 'productionExecutionBundleV2.executionAuthority'); if (!artifacts.splitProductionAuthority) { fail('CROSS_FIELD_MISMATCH', 'productionExecutionBundleV2.executionAuthority'); } await normalizeAuthenticatedApplyResultForExecutionAuthority( bundle.authenticatedResult, artifacts.executionMetadata, artifacts.requestBundle.authenticatedRequest, productionAuthorization, verifierArg, ); if (bundle.receipt) { await normalizeCloudlyLegacyDeploymentSettlementProductionReceiptV2ForAuthorities( bundle.receipt, artifacts.executionMetadata, artifacts.sourceMetadata, artifacts.authenticatedPlan, artifacts.requestBundle, verifierArg, ); if (canonicalize( bundle.receipt.productionAuthorization, 'productionExecutionBundleV2.receipt.productionAuthorization', ) !== canonicalize( artifacts.productionAuthorization, 'productionExecutionBundleV2.productionAuthorization', )) { fail('CROSS_FIELD_MISMATCH', 'productionExecutionBundleV2.productionAuthorization'); } } return bundle; }; export const cloudlyLegacyDeploymentSettlementStdioLimits = Object.freeze({ maximumMongoDescriptorBytes: 16 * 1024, maximumPrivateArtifactAggregateBytes: 4 * 1024 * 1024, maximumRequestFrameBytes: 5 * 1024 * 1024, maximumResponseFrameBytes: 4 * 1024 * 1024, }); export const cloudlyLegacyDeploymentSettlementStdioCommands = Object.freeze([ 'settlement-plan', 'settlement-request', 'settlement-scratch-check', 'settlement-scratch-apply', 'settlement-scratch-resolve', 'settlement-production-authorize', 'settlement-production-check', 'settlement-production-apply', 'settlement-production-resolve', ] as const); export type TCloudlyLegacyDeploymentSettlementStdioCommand = typeof cloudlyLegacyDeploymentSettlementStdioCommands[number]; export interface ICloudlyLegacyDeploymentSettlementMongoDescriptorV1 { mongoDbUrl: string; mongoDbName: string; mongoDbUser: string; mongoDbPass: string; } interface ICloudlyLegacyDeploymentSettlementStdioRequestBaseV1 { schemaVersion: 1; kind: 'cloudly-legacy-deployment-settlement-stdio-request'; requestId: string; command: TCloudlyLegacyDeploymentSettlementStdioCommand; } export interface ICloudlyLegacyDeploymentSettlementPlanStdioRequestV1 extends ICloudlyLegacyDeploymentSettlementStdioRequestBaseV1 { command: 'settlement-plan'; payload: { mongoDescriptor: ICloudlyLegacyDeploymentSettlementMongoDescriptorV1; authorityHandoff: ICloudlyLegacyDeploymentSettlementAuthorityHandoffPlaintextV1; effectiveAt: number; }; } export interface ICloudlyLegacyDeploymentSettlementRequestStdioRequestV1 extends ICloudlyLegacyDeploymentSettlementStdioRequestBaseV1 { command: 'settlement-request'; payload: { authorityHandoff: ICloudlyLegacyDeploymentSettlementAuthorityHandoffPlaintextV1; authenticatedPlan: IAuthenticatedCloudlyLegacyDeploymentSettlementPlanV1; requestedAt: number; }; } interface ICloudlyLegacyDeploymentSettlementScratchStdioPayloadV1 { mongoDescriptor: ICloudlyLegacyDeploymentSettlementMongoDescriptorV1; authorityHandoff: ICloudlyLegacyDeploymentSettlementAuthorityHandoffPlaintextV1; authenticatedPlan: IAuthenticatedCloudlyLegacyDeploymentSettlementPlanV1; requestBundle: ICloudlyLegacyDeploymentSettlementRequestBundleV1; executionAttempt: TCloudlyLegacyDeploymentSettlementScratchExecutionAttemptIdentityV1; } export interface ICloudlyLegacyDeploymentSettlementScratchCheckStdioRequestV1 extends ICloudlyLegacyDeploymentSettlementStdioRequestBaseV1 { command: 'settlement-scratch-check'; payload: ICloudlyLegacyDeploymentSettlementScratchStdioPayloadV1; } export interface ICloudlyLegacyDeploymentSettlementScratchApplyStdioRequestV1 extends ICloudlyLegacyDeploymentSettlementStdioRequestBaseV1 { command: 'settlement-scratch-apply'; payload: ICloudlyLegacyDeploymentSettlementScratchStdioPayloadV1; } export interface ICloudlyLegacyDeploymentSettlementScratchResolveStdioRequestV1 extends ICloudlyLegacyDeploymentSettlementStdioRequestBaseV1 { command: 'settlement-scratch-resolve'; payload: ICloudlyLegacyDeploymentSettlementScratchStdioPayloadV1 & { observedAt: number; }; } export interface ICloudlyLegacyDeploymentSettlementProductionAuthorizeStdioRequestV1 extends ICloudlyLegacyDeploymentSettlementStdioRequestBaseV1 { command: 'settlement-production-authorize'; payload: { sourceAuthorityHandoff: ICloudlyLegacyDeploymentSettlementAuthorityHandoffPlaintextV1; productionAuthorityHandoff: ICloudlyLegacyDeploymentSettlementAuthorityHandoffPlaintextV1; authenticatedPlan: IAuthenticatedCloudlyLegacyDeploymentSettlementPlanV1; requestBundle: ICloudlyLegacyDeploymentSettlementRequestBundleV1; scratchReceipt: ICloudlyLegacyDeploymentSettlementScratchReceiptV1; executionAttempt: TCloudlyLegacyDeploymentSettlementProductionExecutionAttemptIdentityV1; requestedAt: number; approvedAt: number; }; } interface ICloudlyLegacyDeploymentSettlementProductionStdioPayloadV1 { mongoDescriptor: ICloudlyLegacyDeploymentSettlementMongoDescriptorV1; sourceAuthorityHandoff: ICloudlyLegacyDeploymentSettlementAuthorityHandoffPlaintextV1; productionAuthorityHandoff: ICloudlyLegacyDeploymentSettlementAuthorityHandoffPlaintextV1; authenticatedPlan: IAuthenticatedCloudlyLegacyDeploymentSettlementPlanV1; requestBundle: ICloudlyLegacyDeploymentSettlementRequestBundleV1; scratchReceipt: ICloudlyLegacyDeploymentSettlementScratchReceiptV1; productionAuthorization: ICloudlyLegacyDeploymentSettlementProductionExecutionAuthorizationV1; executionAttempt: TCloudlyLegacyDeploymentSettlementProductionExecutionAttemptIdentityV1; } export interface ICloudlyLegacyDeploymentSettlementProductionCheckStdioRequestV1 extends ICloudlyLegacyDeploymentSettlementStdioRequestBaseV1 { command: 'settlement-production-check'; payload: ICloudlyLegacyDeploymentSettlementProductionStdioPayloadV1; } export interface ICloudlyLegacyDeploymentSettlementProductionApplyStdioRequestV1 extends ICloudlyLegacyDeploymentSettlementStdioRequestBaseV1 { command: 'settlement-production-apply'; payload: ICloudlyLegacyDeploymentSettlementProductionStdioPayloadV1; } export interface ICloudlyLegacyDeploymentSettlementProductionResolveStdioRequestV1 extends ICloudlyLegacyDeploymentSettlementStdioRequestBaseV1 { command: 'settlement-production-resolve'; payload: ICloudlyLegacyDeploymentSettlementProductionStdioPayloadV1 & { observedAt: number; }; } export type TCloudlyLegacyDeploymentSettlementStdioRequestV1 = | ICloudlyLegacyDeploymentSettlementPlanStdioRequestV1 | ICloudlyLegacyDeploymentSettlementRequestStdioRequestV1 | ICloudlyLegacyDeploymentSettlementScratchCheckStdioRequestV1 | ICloudlyLegacyDeploymentSettlementScratchApplyStdioRequestV1 | ICloudlyLegacyDeploymentSettlementScratchResolveStdioRequestV1 | ICloudlyLegacyDeploymentSettlementProductionAuthorizeStdioRequestV1 | ICloudlyLegacyDeploymentSettlementProductionCheckStdioRequestV1 | ICloudlyLegacyDeploymentSettlementProductionApplyStdioRequestV1 | ICloudlyLegacyDeploymentSettlementProductionResolveStdioRequestV1; export const cloudlyLegacyDeploymentSettlementStdioErrorMetadata = Object.freeze({ INVALID_FRAME: Object.freeze({ retryable: false }), INVALID_REQUEST: Object.freeze({ retryable: false }), AUTHORITY_INVALID: Object.freeze({ retryable: false }), AUTHORITY_EXPIRED: Object.freeze({ retryable: true }), REQUEST_MISMATCH: Object.freeze({ retryable: false }), PLAN_MISMATCH: Object.freeze({ retryable: false }), SOURCE_STATE_MISMATCH: Object.freeze({ retryable: false }), FINAL_STATE_MISMATCH: Object.freeze({ retryable: true }), TRANSACTIONS_UNSUPPORTED: Object.freeze({ retryable: false }), OPERATION_DRIFT: Object.freeze({ retryable: false }), CLAIM_DRIFT: Object.freeze({ retryable: false }), CLASSIFICATION_MISMATCH: Object.freeze({ retryable: false }), ATTEMPT_CONFLICT: Object.freeze({ retryable: false }), ATTEMPT_NOT_FOUND: Object.freeze({ retryable: false }), INTERNAL_ERROR: Object.freeze({ retryable: true }), } as const); export type TCloudlyLegacyDeploymentSettlementStdioErrorCode = keyof typeof cloudlyLegacyDeploymentSettlementStdioErrorMetadata; export type TCloudlyLegacyDeploymentSettlementStdioSafeErrorV1 = { [TCode in TCloudlyLegacyDeploymentSettlementStdioErrorCode]: { code: TCode; retryable: typeof cloudlyLegacyDeploymentSettlementStdioErrorMetadata[TCode]['retryable']; }; }[TCloudlyLegacyDeploymentSettlementStdioErrorCode]; interface ICloudlyLegacyDeploymentSettlementStdioResponseBaseV1< TCommand extends TCloudlyLegacyDeploymentSettlementStdioCommand, > { schemaVersion: 1; kind: 'cloudly-legacy-deployment-settlement-stdio-response'; requestId: string; command: TCommand; } export interface ICloudlyLegacyDeploymentSettlementStdioSuccessPayloadByCommandV1 { 'settlement-plan': { authenticatedPlan: IAuthenticatedCloudlyLegacyDeploymentSettlementPlanV1; }; 'settlement-request': { requestBundle: ICloudlyLegacyDeploymentSettlementRequestBundleV1; }; 'settlement-scratch-check': { authenticatedResult: IAuthenticatedCloudlyLegacyDeploymentSettlementCheckResultV1; }; 'settlement-scratch-apply': { executionBundle: TCloudlyLegacyDeploymentSettlementScratchExecutionBundleV1; }; 'settlement-scratch-resolve': { authenticatedResolution: IAuthenticatedCloudlyLegacyDeploymentSettlementResolutionV1; }; 'settlement-production-authorize': { productionAuthorization: ICloudlyLegacyDeploymentSettlementProductionExecutionAuthorizationV1; }; 'settlement-production-check': { authenticatedResult: IAuthenticatedCloudlyLegacyDeploymentSettlementCheckResultV1; }; 'settlement-production-apply': { executionBundle: TCloudlyLegacyDeploymentSettlementProductionExecutionBundleV2; }; 'settlement-production-resolve': { authenticatedResolution: IAuthenticatedCloudlyLegacyDeploymentSettlementResolutionV1; }; } export type TCloudlyLegacyDeploymentSettlementStdioSuccessPayloadV1 = ICloudlyLegacyDeploymentSettlementStdioSuccessPayloadByCommandV1[ TCloudlyLegacyDeploymentSettlementStdioCommand ]; export type TCloudlyLegacyDeploymentSettlementStdioSuccessResponseV1 = { [TCommand in TCloudlyLegacyDeploymentSettlementStdioCommand]: ICloudlyLegacyDeploymentSettlementStdioResponseBaseV1 & { ok: true; payload: ICloudlyLegacyDeploymentSettlementStdioSuccessPayloadByCommandV1[TCommand]; }; }[TCloudlyLegacyDeploymentSettlementStdioCommand]; export type TCloudlyLegacyDeploymentSettlementStdioErrorResponseV1 = { [TCommand in TCloudlyLegacyDeploymentSettlementStdioCommand]: ICloudlyLegacyDeploymentSettlementStdioResponseBaseV1 & { ok: false; error: TCloudlyLegacyDeploymentSettlementStdioSafeErrorV1; }; }[TCloudlyLegacyDeploymentSettlementStdioCommand]; export type TCloudlyLegacyDeploymentSettlementStdioResponseV1 = | TCloudlyLegacyDeploymentSettlementStdioSuccessResponseV1 | TCloudlyLegacyDeploymentSettlementStdioErrorResponseV1; const stdioRequestKeys = ['schemaVersion', 'kind', 'requestId', 'command', 'payload'] as const; const stdioResponseSuccessKeys = [ 'schemaVersion', 'kind', 'requestId', 'command', 'ok', 'payload', ] as const; const stdioResponseErrorKeys = [ 'schemaVersion', 'kind', 'requestId', 'command', 'ok', 'error', ] as const; const normalizeSettlementMongoDescriptor = ( valueArg: unknown, pathArg: string, ): ICloudlyLegacyDeploymentSettlementMongoDescriptorV1 => { const value = readRecord(valueArg, pathArg); assertExactKeys(value, ['mongoDbUrl', 'mongoDbName', 'mongoDbUser', 'mongoDbPass'], pathArg); for (const key of ['mongoDbUrl', 'mongoDbName', 'mongoDbUser', 'mongoDbPass'] as const) { if (typeof value[key] !== 'string' || value[key].length === 0 || Buffer.byteLength(value[key], 'utf8') > cloudlyLegacyDeploymentSettlementStdioLimits.maximumMongoDescriptorBytes || /[\u0000-\u0020\u007f]/u.test(value[key])) { fail('INVALID_VALUE', `${pathArg}.${key}`); } } const descriptor = value as unknown as ICloudlyLegacyDeploymentSettlementMongoDescriptorV1; let url: URL; let mongoDbName: string; let mongoDbUser: string; let mongoDbPass: string; try { url = new URL(descriptor.mongoDbUrl); mongoDbName = decodeURIComponent(url.pathname.slice(1)); mongoDbUser = decodeURIComponent(url.username); mongoDbPass = decodeURIComponent(url.password); } catch { return fail('INVALID_VALUE', `${pathArg}.mongoDbUrl`); } const queryKeys = [...new Set(url.searchParams.keys())].sort(); if (url.protocol !== 'mongodb:' || !url.hostname || !url.port || url.hash !== '' || mongoDbName !== descriptor.mongoDbName || mongoDbUser !== descriptor.mongoDbUser || mongoDbPass !== descriptor.mongoDbPass || JSON.stringify(queryKeys) !== JSON.stringify(['authSource', 'directConnection']) || url.searchParams.getAll('authSource').length !== 1 || url.searchParams.get('authSource') !== descriptor.mongoDbName || url.searchParams.getAll('directConnection').length !== 1 || url.searchParams.get('directConnection') !== 'true') { fail('CROSS_FIELD_MISMATCH', pathArg); } const output = { mongoDbUrl: descriptor.mongoDbUrl, mongoDbName: descriptor.mongoDbName, mongoDbUser: descriptor.mongoDbUser, mongoDbPass: descriptor.mongoDbPass, }; if (Buffer.byteLength(canonicalize(output, pathArg), 'utf8') > cloudlyLegacyDeploymentSettlementStdioLimits.maximumMongoDescriptorBytes) { fail('LIMIT_EXCEEDED', pathArg); } return output; }; export const normalizeCloudlyLegacyDeploymentSettlementMongoDescriptor = ( valueArg: unknown, ): Readonly => finalize( normalizeSettlementMongoDescriptor(valueArg, 'mongoDescriptor'), cloudlyLegacyDeploymentSettlementStdioLimits.maximumMongoDescriptorBytes, 'mongoDescriptor', ); const assertStdioArtifactAggregate = (valueArg: unknown, pathArg: string): void => { if (Buffer.byteLength(canonicalize(valueArg, pathArg), 'utf8') > cloudlyLegacyDeploymentSettlementStdioLimits.maximumPrivateArtifactAggregateBytes) { fail('LIMIT_EXCEEDED', pathArg); } }; const assertDistinctStdioHandoffKeyMaterial = ( sourceHandoffArg: ICloudlyLegacyDeploymentSettlementAuthorityHandoffPlaintextV1, executionHandoffArg: ICloudlyLegacyDeploymentSettlementAuthorityHandoffPlaintextV1, pathArg: string, ): void => { const sourceKey = Buffer.from(sourceHandoffArg.hmacKeyPlaintext.value, 'base64url'); const executionKey = Buffer.from(executionHandoffArg.hmacKeyPlaintext.value, 'base64url'); let equal = false; try { equal = plugins.crypto.timingSafeEqual(sourceKey, executionKey); } finally { sourceKey.fill(0); executionKey.fill(0); } if (equal) { fail('CROSS_FIELD_MISMATCH', pathArg); } }; const assertExecutionAttemptMatchesStdioArtifacts = (argsArg: { attempt: ICloudlyLegacyDeploymentSettlementExecutionAttemptIdentityV1; purpose: TCloudlyLegacyDeploymentSettlementExecutionPurpose; sourceHandoff: ICloudlyLegacyDeploymentSettlementAuthorityHandoffPlaintextV1; executionHandoff: ICloudlyLegacyDeploymentSettlementAuthorityHandoffPlaintextV1; authenticatedPlan: IAuthenticatedCloudlyLegacyDeploymentSettlementPlanV1; requestBundle: ICloudlyLegacyDeploymentSettlementRequestBundleV1; scratchReceipt?: ICloudlyLegacyDeploymentSettlementScratchReceiptV1; path: string; }): void => { const sourceReference = argsArg.sourceHandoff.authorityReference; const executionReference = argsArg.executionHandoff.authorityReference; const sourceMetadata = normalizeFencedSourceAuthorityMetadata( argsArg.sourceHandoff.authorityMetadata, `${argsArg.path}.sourceAuthorityMetadata`, ); if (argsArg.purpose === 'production') { assertDistinctStdioHandoffKeyMaterial( argsArg.sourceHandoff, argsArg.executionHandoff, `${argsArg.path}.authorityKeySeparation`, ); normalizeProductionAuthorityMetadataPair( argsArg.executionHandoff.authorityMetadata, sourceMetadata, ); } else { normalizeFencedSourceAuthorityMetadata( argsArg.executionHandoff.authorityMetadata, `${argsArg.path}.executionAuthorityMetadata`, ); } normalizeCloudlyLegacyDeploymentSettlementPlanForAuthority( argsArg.authenticatedPlan.payload, sourceMetadata, ); normalizeCloudlyLegacyDeploymentSettlementProductionRequestForAuthority( argsArg.requestBundle.authenticatedRequest.payload, sourceMetadata, ); if (argsArg.scratchReceipt) { normalizeCloudlyLegacyDeploymentSettlementScratchReceiptStructureForRequest( argsArg.scratchReceipt, argsArg.requestBundle.authenticatedRequest, ); } if (canonicalize(argsArg.authenticatedPlan.authority, `${argsArg.path}.plan.authority`) !== canonicalize(sourceReference, `${argsArg.path}.sourceAuthority`) || canonicalize( argsArg.requestBundle.authenticatedRequest.authority, `${argsArg.path}.request.authority`, ) !== canonicalize(sourceReference, `${argsArg.path}.sourceAuthority`) || canonicalize( argsArg.requestBundle.authenticatedRehearsalBinding.authority, `${argsArg.path}.binding.authority`, ) !== canonicalize(sourceReference, `${argsArg.path}.sourceAuthority`) || canonicalize(argsArg.authenticatedPlan.payload, `${argsArg.path}.plan.payload`) !== canonicalize( argsArg.requestBundle.authenticatedRequest.payload.plan, `${argsArg.path}.request.plan`, ) || argsArg.authenticatedPlan.payloadSha256 !== argsArg.requestBundle.authenticatedRequest.payload.planSha256 || (argsArg.scratchReceipt !== undefined && (canonicalize(argsArg.scratchReceipt.authority, `${argsArg.path}.scratch.authority`) !== canonicalize(sourceReference, `${argsArg.path}.sourceAuthority`) || argsArg.scratchReceipt.requestSha256 !== argsArg.requestBundle.authenticatedRequest.payloadSha256))) { fail('CROSS_FIELD_MISMATCH', `${argsArg.path}.sourceArtifacts`); } const scratchReceiptSha256 = argsArg.scratchReceipt ? digestCloudlyLegacyDeploymentSettlementScratchReceipt(argsArg.scratchReceipt) : null; if (argsArg.attempt.purpose !== argsArg.purpose || argsArg.attempt.operationId !== argsArg.executionHandoff.authorityMetadata.operationId || argsArg.attempt.settlementId !== argsArg.executionHandoff.authorityMetadata.settlementId || canonicalize(argsArg.attempt.sourceAuthority, `${argsArg.path}.attempt.sourceAuthority`) !== canonicalize(sourceReference, `${argsArg.path}.sourceAuthority`) || canonicalize(argsArg.attempt.executionAuthority, `${argsArg.path}.attempt.executionAuthority`) !== canonicalize(executionReference, `${argsArg.path}.executionAuthority`) || argsArg.attempt.authenticatedPlanSha256 !== digestAuthenticatedCloudlyLegacyDeploymentSettlementPlan(argsArg.authenticatedPlan) || argsArg.attempt.requestBundleSha256 !== digestCloudlyLegacyDeploymentSettlementRequestBundle(argsArg.requestBundle) || argsArg.attempt.scratchReceiptSha256 !== scratchReceiptSha256) { fail('CROSS_FIELD_MISMATCH', `${argsArg.path}.executionAttempt`); } if (argsArg.purpose === 'production') { const productionMetadata = argsArg.executionHandoff.authorityMetadata; if (!productionMetadata.sourceAuthority || canonicalize(productionMetadata.sourceAuthority, `${argsArg.path}.metadata.sourceAuthority`) !== canonicalize(sourceReference, `${argsArg.path}.sourceAuthority`) || productionMetadata.sourceAuthenticatedPlanSha256 !== argsArg.attempt.authenticatedPlanSha256 || productionMetadata.sourceRequestBundleSha256 !== argsArg.attempt.requestBundleSha256 || productionMetadata.scratchReceiptSha256 !== scratchReceiptSha256) { fail('CROSS_FIELD_MISMATCH', `${argsArg.path}.productionAuthorityHandoff`); } } }; const normalizeScratchStdioPayload = ( valueArg: unknown, pathArg: string, resolveArg: boolean, ): ICloudlyLegacyDeploymentSettlementScratchStdioPayloadV1 & { observedAt?: number } => { const value = readRecord(valueArg, pathArg); assertExactKeys(value, [ 'mongoDescriptor', 'authorityHandoff', 'authenticatedPlan', 'requestBundle', 'executionAttempt', ...(resolveArg ? ['observedAt'] : []), ], pathArg); const authorityHandoff = normalizeCloudlyLegacyDeploymentSettlementAuthorityHandoffPlaintext( value.authorityHandoff, ); const authenticatedPlan = normalizeCloudlyLegacyDeploymentSettlementAuthenticatedPlanStructure(value.authenticatedPlan); const requestBundle = normalizeCloudlyLegacyDeploymentSettlementRequestBundle(value.requestBundle); const executionAttempt = normalizeExecutionAttemptIdentityInternal( value.executionAttempt, `${pathArg}.executionAttempt`, ); assertExecutionAttemptMatchesStdioArtifacts({ attempt: executionAttempt, purpose: 'scratch-rehearsal', sourceHandoff: authorityHandoff, executionHandoff: authorityHandoff, authenticatedPlan, requestBundle, path: pathArg, }); const output = { mongoDescriptor: normalizeSettlementMongoDescriptor( value.mongoDescriptor, `${pathArg}.mongoDescriptor`, ), authorityHandoff, authenticatedPlan, requestBundle, executionAttempt: executionAttempt as TCloudlyLegacyDeploymentSettlementScratchExecutionAttemptIdentityV1, ...(resolveArg ? { observedAt: readInteger(value.observedAt, `${pathArg}.observedAt`, 1) } : {}), }; assertStdioArtifactAggregate(output, pathArg); return output; }; const normalizeProductionStdioPayload = ( valueArg: unknown, pathArg: string, resolveArg: boolean, ): ICloudlyLegacyDeploymentSettlementProductionStdioPayloadV1 & { observedAt?: number } => { const value = readRecord(valueArg, pathArg); assertExactKeys(value, [ 'mongoDescriptor', 'sourceAuthorityHandoff', 'productionAuthorityHandoff', 'authenticatedPlan', 'requestBundle', 'scratchReceipt', 'productionAuthorization', 'executionAttempt', ...(resolveArg ? ['observedAt'] : []), ], pathArg); const sourceAuthorityHandoff = normalizeCloudlyLegacyDeploymentSettlementAuthorityHandoffPlaintext( value.sourceAuthorityHandoff, ); const productionAuthorityHandoff = normalizeCloudlyLegacyDeploymentSettlementAuthorityHandoffPlaintext( value.productionAuthorityHandoff, ); const authenticatedPlan = normalizeCloudlyLegacyDeploymentSettlementAuthenticatedPlanStructure(value.authenticatedPlan); const requestBundle = normalizeCloudlyLegacyDeploymentSettlementRequestBundle(value.requestBundle); const scratchReceipt = normalizeCloudlyLegacyDeploymentSettlementScratchReceipt( value.scratchReceipt, ); const productionAuthorization = normalizeCloudlyLegacyDeploymentSettlementProductionExecutionAuthorization( value.productionAuthorization, ); const executionAttempt = normalizeExecutionAttemptIdentityInternal( value.executionAttempt, `${pathArg}.executionAttempt`, ); assertExecutionAttemptMatchesStdioArtifacts({ attempt: executionAttempt, purpose: 'production', sourceHandoff: sourceAuthorityHandoff, executionHandoff: productionAuthorityHandoff, authenticatedPlan, requestBundle, scratchReceipt, path: pathArg, }); if (canonicalize(productionAuthorization.executionAttempt, `${pathArg}.authorization.attempt`) !== canonicalize(executionAttempt, `${pathArg}.executionAttempt`)) { fail('CROSS_FIELD_MISMATCH', `${pathArg}.productionAuthorization`); } const metadata = normalizeProductionAuthorityMetadataPair( productionAuthorityHandoff.authorityMetadata, sourceAuthorityHandoff.authorityMetadata, ); assertProductionAuthorizationArtifacts( productionAuthorization, metadata.productionMetadata, metadata.sourceMetadata, authenticatedPlan, requestBundle, scratchReceipt, ); const output = { mongoDescriptor: normalizeSettlementMongoDescriptor( value.mongoDescriptor, `${pathArg}.mongoDescriptor`, ), sourceAuthorityHandoff, productionAuthorityHandoff, authenticatedPlan, requestBundle, scratchReceipt, productionAuthorization, executionAttempt: executionAttempt as TCloudlyLegacyDeploymentSettlementProductionExecutionAttemptIdentityV1, ...(resolveArg ? { observedAt: readInteger(value.observedAt, `${pathArg}.observedAt`, 1) } : {}), }; assertStdioArtifactAggregate(output, pathArg); return output; }; /** Structural only; use the authority-aware variant before trusting artifacts. */ export const normalizeCloudlyLegacyDeploymentSettlementStdioRequest = ( valueArg: unknown, ): Readonly => { const value = readRecord(valueArg, 'stdioRequest'); assertExactKeys(value, stdioRequestKeys, 'stdioRequest'); assertStdioArtifactAggregate(value.payload, 'stdioRequest.payload'); if (value.schemaVersion !== 1 || value.kind !== 'cloudly-legacy-deployment-settlement-stdio-request') { fail('INVALID_VALUE', 'stdioRequest.kind'); } const requestId = readIdentifier(value.requestId, 'stdioRequest.requestId'); const command = readLiteral( value.command, cloudlyLegacyDeploymentSettlementStdioCommands, 'stdioRequest.command', ); const payloadPath = 'stdioRequest.payload'; let payload: TCloudlyLegacyDeploymentSettlementStdioRequestV1['payload']; if (command === 'settlement-plan') { const input = readRecord(value.payload, payloadPath); assertExactKeys(input, ['mongoDescriptor', 'authorityHandoff', 'effectiveAt'], payloadPath); const authorityHandoff = normalizeCloudlyLegacyDeploymentSettlementAuthorityHandoffPlaintext( input.authorityHandoff, ); const sourceMetadata = normalizeFencedSourceAuthorityMetadata( authorityHandoff.authorityMetadata, `${payloadPath}.authorityHandoff.authorityMetadata`, ); const effectiveAt = readInteger(input.effectiveAt, `${payloadPath}.effectiveAt`, 1); assertAuthorityTimestamp(effectiveAt, sourceMetadata, `${payloadPath}.effectiveAt`); payload = { mongoDescriptor: normalizeSettlementMongoDescriptor( input.mongoDescriptor, `${payloadPath}.mongoDescriptor`, ), authorityHandoff, effectiveAt, }; } else if (command === 'settlement-request') { const input = readRecord(value.payload, payloadPath); assertExactKeys(input, ['authorityHandoff', 'authenticatedPlan', 'requestedAt'], payloadPath); const authorityHandoff = normalizeCloudlyLegacyDeploymentSettlementAuthorityHandoffPlaintext( input.authorityHandoff, ); const sourceMetadata = normalizeFencedSourceAuthorityMetadata( authorityHandoff.authorityMetadata, `${payloadPath}.authorityHandoff.authorityMetadata`, ); const authenticatedPlan = normalizeCloudlyLegacyDeploymentSettlementAuthenticatedPlanStructure( input.authenticatedPlan, ); assertAuthorityReferenceMatchesMetadata( authenticatedPlan.authority, sourceMetadata, `${payloadPath}.authenticatedPlan.authority`, ); normalizeCloudlyLegacyDeploymentSettlementPlanForAuthority( authenticatedPlan.payload, sourceMetadata, ); const requestedAt = readInteger(input.requestedAt, `${payloadPath}.requestedAt`, 1); assertAuthorityTimestamp(requestedAt, sourceMetadata, `${payloadPath}.requestedAt`); if (requestedAt < authenticatedPlan.payload.effectiveAt) { fail('CROSS_FIELD_MISMATCH', `${payloadPath}.requestedAt`); } payload = { authorityHandoff, authenticatedPlan, requestedAt, }; } else if (command === 'settlement-scratch-check' || command === 'settlement-scratch-apply') { payload = normalizeScratchStdioPayload(value.payload, payloadPath, false); } else if (command === 'settlement-scratch-resolve') { payload = normalizeScratchStdioPayload(value.payload, payloadPath, true) as ICloudlyLegacyDeploymentSettlementScratchResolveStdioRequestV1['payload']; } else if (command === 'settlement-production-authorize') { const input = readRecord(value.payload, payloadPath); assertExactKeys(input, [ 'sourceAuthorityHandoff', 'productionAuthorityHandoff', 'authenticatedPlan', 'requestBundle', 'scratchReceipt', 'executionAttempt', 'requestedAt', 'approvedAt', ], payloadPath); const sourceAuthorityHandoff = normalizeCloudlyLegacyDeploymentSettlementAuthorityHandoffPlaintext( input.sourceAuthorityHandoff, ); const productionAuthorityHandoff = normalizeCloudlyLegacyDeploymentSettlementAuthorityHandoffPlaintext( input.productionAuthorityHandoff, ); const authenticatedPlan = normalizeCloudlyLegacyDeploymentSettlementAuthenticatedPlanStructure( input.authenticatedPlan, ); const requestBundle = normalizeCloudlyLegacyDeploymentSettlementRequestBundle( input.requestBundle, ); const scratchReceipt = normalizeCloudlyLegacyDeploymentSettlementScratchReceipt( input.scratchReceipt, ); const executionAttempt = normalizeExecutionAttemptIdentityInternal( input.executionAttempt, `${payloadPath}.executionAttempt`, ); assertExecutionAttemptMatchesStdioArtifacts({ attempt: executionAttempt, purpose: 'production', sourceHandoff: sourceAuthorityHandoff, executionHandoff: productionAuthorityHandoff, authenticatedPlan, requestBundle, scratchReceipt, path: payloadPath, }); const requestedAt = readInteger(input.requestedAt, `${payloadPath}.requestedAt`, 1); const metadata = normalizeProductionAuthorityMetadataPair( productionAuthorityHandoff.authorityMetadata, sourceAuthorityHandoff.authorityMetadata, ); const approvedAt = readInteger(input.approvedAt, `${payloadPath}.approvedAt`, requestedAt); assertAuthorityTimestamp(requestedAt, metadata.productionMetadata, `${payloadPath}.requestedAt`); assertAuthorityTimestamp(approvedAt, metadata.productionMetadata, `${payloadPath}.approvedAt`); if (metadata.productionMetadata.issuedAt <= scratchReceipt.completedAt || requestedAt <= scratchReceipt.completedAt) { fail('CROSS_FIELD_MISMATCH', `${payloadPath}.requestedAt`); } payload = { sourceAuthorityHandoff, productionAuthorityHandoff, authenticatedPlan, requestBundle, scratchReceipt, executionAttempt: executionAttempt as TCloudlyLegacyDeploymentSettlementProductionExecutionAttemptIdentityV1, requestedAt, approvedAt, }; } else if (command === 'settlement-production-resolve') { payload = normalizeProductionStdioPayload(value.payload, payloadPath, true) as ICloudlyLegacyDeploymentSettlementProductionResolveStdioRequestV1['payload']; } else { payload = normalizeProductionStdioPayload(value.payload, payloadPath, false); } assertStdioArtifactAggregate(payload, payloadPath); return finalize({ schemaVersion: 1, kind: 'cloudly-legacy-deployment-settlement-stdio-request', requestId, command, payload, } as TCloudlyLegacyDeploymentSettlementStdioRequestV1, cloudlyLegacyDeploymentSettlementStdioLimits.maximumRequestFrameBytes - 1, 'stdioRequest'); }; const createCloudlyLegacyDeploymentSettlementStdioRequestHmacVerifier = ( requestArg: TCloudlyLegacyDeploymentSettlementStdioRequestV1, ): TCloudlyLegacyDeploymentSettlementHmacVerifier => { if (requestArg.command === 'settlement-plan' || requestArg.command === 'settlement-request' || requestArg.command === 'settlement-scratch-check' || requestArg.command === 'settlement-scratch-apply' || requestArg.command === 'settlement-scratch-resolve') { return createCloudlyLegacyDeploymentSettlementStdioHandoffHmacVerifier( requestArg.payload.authorityHandoff, ); } const sourceVerifier = createCloudlyLegacyDeploymentSettlementStdioHandoffHmacVerifier( requestArg.payload.sourceAuthorityHandoff, ); const executionVerifier = createCloudlyLegacyDeploymentSettlementStdioHandoffHmacVerifier( requestArg.payload.productionAuthorityHandoff, ); return async (inputArg): Promise => ( await sourceVerifier(inputArg) || await executionVerifier(inputArg) ); }; export const normalizeCloudlyLegacyDeploymentSettlementStdioRequestForAuthorities = async ( valueArg: unknown, ): Promise> => { const request = normalizeCloudlyLegacyDeploymentSettlementStdioRequest(valueArg); const verifier = createCloudlyLegacyDeploymentSettlementStdioRequestHmacVerifier(request); if (request.command === 'settlement-plan') { return request; } if (request.command === 'settlement-request') { await normalizeAuthenticatedCloudlyLegacyDeploymentSettlementPlanForAuthority( request.payload.authenticatedPlan, request.payload.authorityHandoff.authorityMetadata, verifier, ); return request; } if (request.command === 'settlement-scratch-check' || request.command === 'settlement-scratch-apply' || request.command === 'settlement-scratch-resolve') { await normalizeExecutionAttemptProofArtifacts({ executionAttempt: request.payload.executionAttempt, sourceMetadata: request.payload.authorityHandoff.authorityMetadata, executionMetadata: request.payload.authorityHandoff.authorityMetadata, authenticatedPlan: request.payload.authenticatedPlan, requestBundle: request.payload.requestBundle, scratchReceipt: null, productionAuthorization: null, requireProductionAuthorization: false, verifier, }); return request; } await normalizeExecutionAttemptProofArtifacts({ executionAttempt: request.payload.executionAttempt, sourceMetadata: request.payload.sourceAuthorityHandoff.authorityMetadata, executionMetadata: request.payload.productionAuthorityHandoff.authorityMetadata, authenticatedPlan: request.payload.authenticatedPlan, requestBundle: request.payload.requestBundle, scratchReceipt: request.payload.scratchReceipt, productionAuthorization: request.command === 'settlement-production-authorize' ? null : request.payload.productionAuthorization, requireProductionAuthorization: request.command !== 'settlement-production-authorize', verifier, }); return request; }; const normalizeStdioSuccessPayload = ( commandArg: TCloudlyLegacyDeploymentSettlementStdioCommand, valueArg: unknown, ): TCloudlyLegacyDeploymentSettlementStdioSuccessPayloadV1 => { const path = 'stdioResponse.payload'; const value = readRecord(valueArg, path); if (commandArg === 'settlement-plan') { assertExactKeys(value, ['authenticatedPlan'], path); return { authenticatedPlan: normalizeCloudlyLegacyDeploymentSettlementAuthenticatedPlanStructure( value.authenticatedPlan, ), }; } if (commandArg === 'settlement-request') { assertExactKeys(value, ['requestBundle'], path); return { requestBundle: normalizeCloudlyLegacyDeploymentSettlementRequestBundle( value.requestBundle, ) }; } if (commandArg === 'settlement-scratch-check' || commandArg === 'settlement-production-check') { assertExactKeys(value, ['authenticatedResult'], path); return { authenticatedResult: normalizeCloudlyLegacyDeploymentSettlementAuthenticatedCheckResultStructure( value.authenticatedResult, ), }; } if (commandArg === 'settlement-scratch-apply') { assertExactKeys(value, ['executionBundle'], path); return { executionBundle: normalizeCloudlyLegacyDeploymentSettlementScratchExecutionBundle( value.executionBundle, ), }; } if (commandArg === 'settlement-production-apply') { assertExactKeys(value, ['executionBundle'], path); return { executionBundle: normalizeCloudlyLegacyDeploymentSettlementProductionExecutionBundleV2( value.executionBundle, ), }; } if (commandArg === 'settlement-production-authorize') { assertExactKeys(value, ['productionAuthorization'], path); return { productionAuthorization: normalizeCloudlyLegacyDeploymentSettlementProductionExecutionAuthorization( value.productionAuthorization, ), }; } assertExactKeys(value, ['authenticatedResolution'], path); return { authenticatedResolution: normalizeCloudlyLegacyDeploymentSettlementAuthenticatedResolutionStructure( value.authenticatedResolution, ), }; }; const createCloudlyLegacyDeploymentSettlementStdioSafeError = ( codeArg: TCloudlyLegacyDeploymentSettlementStdioErrorCode, ): TCloudlyLegacyDeploymentSettlementStdioSafeErrorV1 => ({ code: codeArg, retryable: cloudlyLegacyDeploymentSettlementStdioErrorMetadata[codeArg].retryable, } as TCloudlyLegacyDeploymentSettlementStdioSafeErrorV1); /** Structural only; use the request-authority-aware variant before trusting artifacts. */ export const normalizeCloudlyLegacyDeploymentSettlementStdioResponse = ( valueArg: unknown, ): Readonly => { const value = readRecord(valueArg, 'stdioResponse'); if (typeof value.ok !== 'boolean') fail('INVALID_VALUE', 'stdioResponse.ok'); assertExactKeys( value, value.ok ? stdioResponseSuccessKeys : stdioResponseErrorKeys, 'stdioResponse', ); if (value.schemaVersion !== 1 || value.kind !== 'cloudly-legacy-deployment-settlement-stdio-response') { fail('INVALID_VALUE', 'stdioResponse.kind'); } if (value.ok) { assertStdioArtifactAggregate(value.payload, 'stdioResponse.payload'); } const requestId = readIdentifier(value.requestId, 'stdioResponse.requestId'); const command = readLiteral( value.command, cloudlyLegacyDeploymentSettlementStdioCommands, 'stdioResponse.command', ); if (value.ok) { const payload = normalizeStdioSuccessPayload(command, value.payload); assertStdioArtifactAggregate(payload, 'stdioResponse.payload'); return finalize({ schemaVersion: 1, kind: 'cloudly-legacy-deployment-settlement-stdio-response', requestId, command, ok: true, payload, } as TCloudlyLegacyDeploymentSettlementStdioSuccessResponseV1, cloudlyLegacyDeploymentSettlementStdioLimits.maximumResponseFrameBytes - 1, 'stdioResponse'); } const error = readRecord(value.error, 'stdioResponse.error'); assertExactKeys(error, ['code', 'retryable'], 'stdioResponse.error'); if (typeof error.code !== 'string' || !Object.hasOwn(cloudlyLegacyDeploymentSettlementStdioErrorMetadata, error.code)) { fail('INVALID_VALUE', 'stdioResponse.error.code'); } const code = error.code as TCloudlyLegacyDeploymentSettlementStdioErrorCode; if (error.retryable !== cloudlyLegacyDeploymentSettlementStdioErrorMetadata[code].retryable) { fail('CROSS_FIELD_MISMATCH', 'stdioResponse.error.retryable'); } return finalize({ schemaVersion: 1, kind: 'cloudly-legacy-deployment-settlement-stdio-response', requestId, command, ok: false, error: createCloudlyLegacyDeploymentSettlementStdioSafeError(code), } as TCloudlyLegacyDeploymentSettlementStdioErrorResponseV1, cloudlyLegacyDeploymentSettlementStdioLimits.maximumResponseFrameBytes - 1, 'stdioResponse'); }; export const normalizeCloudlyLegacyDeploymentSettlementStdioResponseForRequestAuthorities = async ( responseArg: unknown, requestArg: unknown, ): Promise> => { const request = await normalizeCloudlyLegacyDeploymentSettlementStdioRequestForAuthorities( requestArg, ); const verifier = createCloudlyLegacyDeploymentSettlementStdioRequestHmacVerifier(request); const response = normalizeCloudlyLegacyDeploymentSettlementStdioResponse(responseArg); if (response.requestId !== request.requestId || response.command !== request.command) { fail('CROSS_FIELD_MISMATCH', 'stdioResponse.request'); } if (!response.ok) { return response; } if (request.command === 'settlement-plan') { const success = response as Extract< TCloudlyLegacyDeploymentSettlementStdioSuccessResponseV1, { command: 'settlement-plan' } >; const plan = await normalizeAuthenticatedCloudlyLegacyDeploymentSettlementPlanForAuthority( success.payload.authenticatedPlan, request.payload.authorityHandoff.authorityMetadata, verifier, ); if (plan.payload.effectiveAt !== request.payload.effectiveAt) { fail('CROSS_FIELD_MISMATCH', 'stdioResponse.payload.authenticatedPlan.effectiveAt'); } return response; } if (request.command === 'settlement-request') { const success = response as Extract< TCloudlyLegacyDeploymentSettlementStdioSuccessResponseV1, { command: 'settlement-request' } >; const requestBundle = await normalizeCloudlyLegacyDeploymentSettlementRequestBundleForAuthority( success.payload.requestBundle, request.payload.authenticatedPlan, request.payload.authorityHandoff.authorityMetadata, verifier, ); if (requestBundle.authenticatedRequest.payload.requestedAt !== request.payload.requestedAt) { fail('CROSS_FIELD_MISMATCH', 'stdioResponse.payload.requestBundle.requestedAt'); } return response; } if (request.command === 'settlement-scratch-check') { const success = response as Extract< TCloudlyLegacyDeploymentSettlementStdioSuccessResponseV1, { command: 'settlement-scratch-check' } >; await normalizeAuthenticatedCloudlyLegacyDeploymentSettlementCheckResultForAuthority( success.payload.authenticatedResult, request.payload.authorityHandoff.authorityMetadata, request.payload.requestBundle.authenticatedRequest, verifier, ); return response; } if (request.command === 'settlement-scratch-apply') { const success = response as Extract< TCloudlyLegacyDeploymentSettlementStdioSuccessResponseV1, { command: 'settlement-scratch-apply' } >; await normalizeCloudlyLegacyDeploymentSettlementScratchExecutionBundleForAuthority( success.payload.executionBundle, request.payload.authorityHandoff.authorityMetadata, request.payload.authenticatedPlan, request.payload.requestBundle, verifier, ); return response; } if (request.command === 'settlement-scratch-resolve') { const success = response as Extract< TCloudlyLegacyDeploymentSettlementStdioSuccessResponseV1, { command: 'settlement-scratch-resolve' } >; const resolution = await normalizeAuthenticatedCloudlyLegacyDeploymentSettlementResolutionForAuthorities( success.payload.authenticatedResolution, request.payload.authorityHandoff.authorityMetadata, request.payload.authorityHandoff.authorityMetadata, request.payload.authenticatedPlan, request.payload.requestBundle, null, null, verifier, ); if (resolution.payload.observedAt !== request.payload.observedAt) { fail('CROSS_FIELD_MISMATCH', 'stdioResponse.payload.authenticatedResolution.observedAt'); } return response; } if (request.command === 'settlement-production-authorize') { const success = response as Extract< TCloudlyLegacyDeploymentSettlementStdioSuccessResponseV1, { command: 'settlement-production-authorize' } >; const authorization = await normalizeCloudlyLegacyDeploymentSettlementProductionExecutionAuthorizationForAuthorities( success.payload.productionAuthorization, request.payload.productionAuthorityHandoff.authorityMetadata, request.payload.sourceAuthorityHandoff.authorityMetadata, request.payload.authenticatedPlan, request.payload.requestBundle, request.payload.scratchReceipt, verifier, ); if (authorization.requestedAt !== request.payload.requestedAt || authorization.approvedAt !== request.payload.approvedAt) { fail('CROSS_FIELD_MISMATCH', 'stdioResponse.payload.productionAuthorization.timestamp'); } return response; } if (request.command === 'settlement-production-check') { const success = response as Extract< TCloudlyLegacyDeploymentSettlementStdioSuccessResponseV1, { command: 'settlement-production-check' } >; await normalizeAuthenticatedCheckResultForExecutionAuthority( success.payload.authenticatedResult, request.payload.productionAuthorityHandoff.authorityMetadata, request.payload.requestBundle.authenticatedRequest, request.payload.productionAuthorization, verifier, ); return response; } if (request.command === 'settlement-production-apply') { const success = response as Extract< TCloudlyLegacyDeploymentSettlementStdioSuccessResponseV1, { command: 'settlement-production-apply' } >; await normalizeCloudlyLegacyDeploymentSettlementProductionExecutionBundleV2ForAuthorities( success.payload.executionBundle, request.payload.productionAuthorization, request.payload.productionAuthorityHandoff.authorityMetadata, request.payload.sourceAuthorityHandoff.authorityMetadata, request.payload.authenticatedPlan, request.payload.requestBundle, request.payload.scratchReceipt, verifier, ); return response; } const success = response as Extract< TCloudlyLegacyDeploymentSettlementStdioSuccessResponseV1, { command: 'settlement-production-resolve' } >; const resolution = await normalizeAuthenticatedCloudlyLegacyDeploymentSettlementResolutionForAuthorities( success.payload.authenticatedResolution, request.payload.sourceAuthorityHandoff.authorityMetadata, request.payload.productionAuthorityHandoff.authorityMetadata, request.payload.authenticatedPlan, request.payload.requestBundle, request.payload.scratchReceipt, request.payload.productionAuthorization, verifier, ); if (resolution.payload.observedAt !== request.payload.observedAt) { fail('CROSS_FIELD_MISMATCH', 'stdioResponse.payload.authenticatedResolution.observedAt'); } return response; }; const encodeStdioFrame = ( valueArg: unknown, maximumBytesArg: number, pathArg: string, ): Uint8Array => { const payload = encodeNormalized(valueArg, pathArg); try { if (payload.byteLength + 1 > maximumBytesArg) fail('LIMIT_EXCEEDED', pathArg); const output = new Uint8Array(payload.byteLength + 1); output.set(payload); output[payload.byteLength] = 0x0a; return output; } finally { payload.fill(0); } }; export const encodeCloudlyLegacyDeploymentSettlementStdioRequestFrame = ( valueArg: unknown, ): Uint8Array => encodeStdioFrame( normalizeCloudlyLegacyDeploymentSettlementStdioRequest(valueArg), cloudlyLegacyDeploymentSettlementStdioLimits.maximumRequestFrameBytes, 'stdioRequest', ); export const encodeCloudlyLegacyDeploymentSettlementStdioResponseFrame = ( valueArg: unknown, ): Uint8Array => encodeStdioFrame( normalizeCloudlyLegacyDeploymentSettlementStdioResponse(valueArg), cloudlyLegacyDeploymentSettlementStdioLimits.maximumResponseFrameBytes, 'stdioResponse', ); const decodeStdioFrame = ( frameArg: Uint8Array, maximumBytesArg: number, pathArg: string, normalizeArg: (valueArg: unknown) => Readonly, encodeArg: (valueArg: unknown) => Uint8Array, ): Readonly => { if (!(frameArg instanceof Uint8Array) || frameArg.byteLength < 3 || frameArg.byteLength > maximumBytesArg || frameArg.at(-1) !== 0x0a || frameArg.subarray(0, -1).some((byteArg) => byteArg === 0x0a || byteArg === 0x0d)) { fail('INVALID_DATA', pathArg); } const payloadBytes = new Uint8Array(frameArg.subarray(0, -1)); let canonicalFrame: Uint8Array | undefined; try { let text: string; try { text = new TextDecoder('utf-8', { fatal: true }).decode(payloadBytes); } catch { return fail('INVALID_DATA', pathArg); } let value: unknown; try { value = JSON.parse(text) as unknown; } catch { return fail('INVALID_DATA', pathArg); } const normalized = normalizeArg(value); canonicalFrame = encodeArg(normalized); if (canonicalFrame.byteLength !== frameArg.byteLength || canonicalFrame.some((byteArg, indexArg) => byteArg !== frameArg[indexArg])) { fail('INVALID_DATA', pathArg); } return normalized; } finally { payloadBytes.fill(0); canonicalFrame?.fill(0); } }; export const decodeCloudlyLegacyDeploymentSettlementStdioRequestFrame = ( frameArg: Uint8Array, ): Readonly => decodeStdioFrame( frameArg, cloudlyLegacyDeploymentSettlementStdioLimits.maximumRequestFrameBytes, 'stdioRequestFrame', normalizeCloudlyLegacyDeploymentSettlementStdioRequest, encodeCloudlyLegacyDeploymentSettlementStdioRequestFrame, ); export const decodeCloudlyLegacyDeploymentSettlementStdioResponseFrame = ( frameArg: Uint8Array, ): Readonly => decodeStdioFrame( frameArg, cloudlyLegacyDeploymentSettlementStdioLimits.maximumResponseFrameBytes, 'stdioResponseFrame', normalizeCloudlyLegacyDeploymentSettlementStdioResponse, encodeCloudlyLegacyDeploymentSettlementStdioResponseFrame, ); export { cloudlyLegacyDeploymentSettlementGoldenVectors } from './runtime.cloudlylegacydeploymentsettlement.golden.js';