import { assertIdentifierDigest, assertSafeProjection, } from "../../../packages/device-protocol-contract/src/index.mjs"; import { normalizeCertificateIdentities, } from "../../../packages/device-edge-channel-contract/src/index.mjs"; import { normalizeManagementActor } from "./project-management.mjs"; export const DEVICE_INFRASTRUCTURE_COMMAND_KINDS = Object.freeze([ "adapter_package.ensure", "adapter_version.register", "model_profile.register", "edge.ensure", "route.ensure", "enrollment_intent.ensure", ]); const commandKindSet = new Set(DEVICE_INFRASTRUCTURE_COMMAND_KINDS); const keyPattern = /^[a-z][a-z0-9-]{1,62}$/; const opaqueRefPattern = /^[A-Za-z0-9][A-Za-z0-9._:/+-]{2,255}$/; const profileRefPattern = /^[A-Za-z0-9][A-Za-z0-9._:-]{2,127}$/; const protocolPattern = /^[A-Z][A-Z0-9_]{0,31}$/; const capabilityPattern = /^[a-z][a-z0-9._-]{1,63}$/; const semverPattern = /^[0-9]+\.[0-9]+\.[0-9]+(?:[+-][A-Za-z0-9.-]+)?$/; const digestPattern = /^sha256:[a-f0-9]{64}$/; const isoTimestampPattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/; export function isInfrastructureManagementCommand(kind) { return commandKindSet.has(kind); } export function normalizeInfrastructureManagementCommand(kind, input) { if (!commandKindSet.has(kind)) { throw new TypeError("device_infrastructure_command_kind_invalid"); } assertPlainObject(input, "device_infrastructure_command_invalid"); if (kind === "adapter_package.ensure") { assertAllowedKeys(input, [ "packageKey", "displayName", "publisherRef", "lifecycleState", ]); return Object.freeze({ packageKey: normalizeKey(input.packageKey, "device_adapter_package_key_invalid"), displayName: normalizeDisplayText( input.displayName, 160, "device_adapter_package_name_invalid", ), publisherRef: normalizeOpaqueRef( input.publisherRef, "device_adapter_publisher_ref_invalid", ), lifecycleState: normalizeEnum( input.lifecycleState ?? "active", new Set(["active", "retired"]), "device_adapter_package_state_invalid", ), }); } if (kind === "adapter_version.register") { assertAllowedKeys(input, [ "adapterPackageRef", "version", "runtimePackageRef", "contentDigest", "contractVersion", "capabilities", "lifecycleState", ]); return Object.freeze({ adapterPackageId: normalizeEntityRef( input.adapterPackageRef, "adapter-package", "device_adapter_package_ref_invalid", ), version: normalizePattern( input.version, semverPattern, "device_adapter_version_invalid", ), runtimePackageRef: normalizeOpaqueRef( input.runtimePackageRef, "device_adapter_runtime_package_ref_invalid", ), contentDigest: normalizePattern( input.contentDigest, digestPattern, "device_adapter_content_digest_invalid", ), contractVersion: normalizeProfileRef( input.contractVersion, "device_adapter_contract_version_invalid", ), capabilities: Object.freeze(normalizeCapabilities(input.capabilities ?? [])), lifecycleState: normalizeEnum( input.lifecycleState ?? "draft", new Set(["draft", "active", "retired"]), "device_adapter_version_state_invalid", ), }); } if (kind === "model_profile.register") { assertAllowedKeys(input, [ "adapterVersionRef", "profileRef", "schemaVersion", "vendor", "model", "deviceType", "protocol", "schemaArtifactRef", "profileDigest", "capabilities", "lifecycleState", ]); return Object.freeze({ adapterVersionId: normalizeEntityRef( input.adapterVersionRef, "adapter-version", "device_adapter_version_ref_invalid", ), profileRef: normalizeProfileRef( input.profileRef, "device_model_profile_ref_invalid", ), schemaVersion: normalizeProfileRef( input.schemaVersion, "device_model_profile_schema_version_invalid", ), vendor: normalizeDisplayText(input.vendor, 120, "device_model_vendor_invalid"), model: normalizeDisplayText(input.model, 120, "device_model_name_invalid"), deviceType: normalizePattern( input.deviceType, capabilityPattern, "device_model_type_invalid", ), protocol: normalizePattern( input.protocol, protocolPattern, "device_model_protocol_invalid", ), schemaArtifactRef: normalizeOpaqueRef( input.schemaArtifactRef, "device_model_schema_artifact_ref_invalid", ), profileDigest: normalizePattern( input.profileDigest, digestPattern, "device_model_profile_digest_invalid", ), capabilities: Object.freeze(normalizeCapabilities(input.capabilities ?? [])), lifecycleState: normalizeEnum( input.lifecycleState ?? "draft", new Set(["draft", "active", "retired"]), "device_model_profile_state_invalid", ), }); } if (kind === "edge.ensure") { assertAllowedKeys(input, [ "edgeKey", "displayName", "deploymentRef", "lifecycleState", "channel", ]); const normalized = { edgeKey: normalizeKey(input.edgeKey, "device_edge_key_invalid"), displayName: normalizeDisplayText( input.displayName, 160, "device_edge_name_invalid", ), deploymentRef: normalizeOptionalOpaqueRef( input.deploymentRef, "device_edge_deployment_ref_invalid", ), lifecycleState: normalizeEnum( input.lifecycleState ?? "provisioning", new Set(["provisioning", "active", "suspended", "retired"]), "device_edge_state_invalid", ), }; if (input.channel !== undefined) { normalized.channel = normalizeEdgeChannel(input.channel); } return Object.freeze(normalized); } if (kind === "route.ensure") { assertAllowedKeys(input, [ "projectRef", "routeKey", "displayName", "edgeRef", "modelProfileRef", "listenerRef", "protocol", "direction", "lifecycleState", ]); return Object.freeze({ projectId: normalizeEntityRef( input.projectRef, "project", "device_project_ref_invalid", ), routeKey: normalizeKey(input.routeKey, "device_route_key_invalid"), displayName: normalizeDisplayText( input.displayName, 160, "device_route_name_invalid", ), edgeId: normalizeEntityRef( input.edgeRef, "edge", "device_edge_ref_invalid", ), modelProfileRef: normalizeProfileRef( input.modelProfileRef, "device_model_profile_ref_invalid", ), listenerRef: normalizeOpaqueRef( input.listenerRef, "device_route_listener_ref_invalid", ), protocol: normalizePattern( input.protocol, protocolPattern, "device_route_protocol_invalid", ), direction: normalizeEnum( input.direction ?? "telemetry", new Set(["telemetry", "bidirectional"]), "device_route_direction_invalid", ), lifecycleState: normalizeEnum( input.lifecycleState ?? "draft", new Set(["draft", "active", "suspended", "retired"]), "device_route_state_invalid", ), }); } assertAllowedKeys(input, [ "projectRef", "enrollmentKey", "routeRef", "modelProfileRef", "displayName", "identifierKind", "identifierDigest", "identifierMasked", "expiresAt", ]); const identifierMasked = normalizeDisplayText( input.identifierMasked, 64, "device_enrollment_identifier_masked_invalid", ); assertSafeProjection({ identifierMasked }); return Object.freeze({ projectId: normalizeEntityRef( input.projectRef, "project", "device_project_ref_invalid", ), enrollmentKey: normalizeKey( input.enrollmentKey, "device_enrollment_key_invalid", ), routeId: normalizeEntityRef( input.routeRef, "route", "device_route_ref_invalid", ), modelProfileRef: normalizeProfileRef( input.modelProfileRef, "device_model_profile_ref_invalid", ), displayName: normalizeDisplayText( input.displayName, 160, "device_enrollment_name_invalid", ), identifierKind: normalizePattern( input.identifierKind, /^[a-z][a-z0-9._-]{1,31}$/, "device_enrollment_identifier_kind_invalid", ), identifierDigest: assertIdentifierDigest(input.identifierDigest), identifierMasked, expiresAt: normalizeOptionalTimestamp(input.expiresAt), }); } export function assertPlatformCatalogAuthority(actorInput) { const actor = normalizeManagementActor(actorInput); if (actor.hubRole !== "owner") { throw domainError("device_platform_catalog_access_denied", 403); } return actor; } function normalizeCapabilities(input) { if (!Array.isArray(input) || input.length > 64) { throw new TypeError("device_adapter_capabilities_invalid"); } return [...new Set(input.map((capability) => normalizePattern( capability, capabilityPattern, "device_adapter_capability_invalid", )))].sort(); } function normalizeEntityRef(value, prefix, code) { if (typeof value !== "string") throw new TypeError(code); const match = value.match(new RegExp( `^${prefix}:([0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$`, "i", )); if (!match) throw new TypeError(code); return match[1].toLowerCase(); } function normalizeKey(value, code) { return normalizePattern(value, keyPattern, code); } function normalizeProfileRef(value, code) { return normalizePattern(value, profileRefPattern, code); } function normalizeOpaqueRef(value, code) { return normalizePattern(value, opaqueRefPattern, code); } function normalizeOptionalOpaqueRef(value, code) { if (value == null || value === "") return null; return normalizeOpaqueRef(value, code); } function normalizeEdgeChannel(input) { assertPlainObject(input, "device_edge_channel_invalid"); assertAllowedKeys(input, [ "endpoint", "servername", "generationRef", "trustBundleRef", "certificateIdentities", "lifecycleState", ]); const lifecycleState = normalizeEnum( input.lifecycleState ?? "disabled", new Set(["disabled", "active", "revoked"]), "device_edge_channel_state_invalid", ); if (lifecycleState === "disabled") { if (Object.keys(input).some((key) => key !== "lifecycleState")) { throw new TypeError("device_edge_channel_disabled_configuration_invalid"); } return Object.freeze({ endpoint: null, servername: null, generationRef: null, trustBundleRef: null, certificateIdentities: Object.freeze([]), lifecycleState, }); } const endpoint = normalizeEdgeEndpoint(input.endpoint); const servername = normalizePattern( input.servername, /^[A-Za-z0-9.-]{1,253}$/, "device_edge_channel_servername_invalid", ).toLowerCase(); if (servername !== endpoint.hostname) { throw new TypeError("device_edge_channel_servername_mismatch"); } return Object.freeze({ endpoint: endpoint.toString(), servername, generationRef: normalizeProfileRef( input.generationRef, "device_edge_channel_generation_invalid", ), trustBundleRef: normalizePattern( input.trustBundleRef, /^edge-trust:[a-z][a-z0-9-]{1,62}$/, "device_edge_channel_trust_bundle_ref_invalid", ), certificateIdentities: normalizeCertificateIdentities( input.certificateIdentities, ), lifecycleState, }); } function normalizeEdgeEndpoint(value) { let endpoint; try { endpoint = new URL(String(value || "")); } catch { throw new TypeError("device_edge_channel_endpoint_invalid"); } if ( endpoint.protocol !== "https:" || endpoint.username || endpoint.password || endpoint.pathname !== "/" || endpoint.search || endpoint.hash || endpoint.port !== "" || !isPublicIpv4(endpoint.hostname) ) { throw new TypeError("device_edge_channel_endpoint_invalid"); } return endpoint; } function isPublicIpv4(value) { const octets = value.split(".").map(Number); if ( octets.length !== 4 || octets.some((part) => !Number.isInteger(part) || part < 0 || part > 255) ) return false; const [a, b, c] = octets; if (a < 1 || a >= 224) return false; if (a === 10 || a === 127) return false; if (a === 100 && b >= 64 && b <= 127) return false; if (a === 169 && b === 254) return false; if (a === 172 && b >= 16 && b <= 31) return false; if (a === 192 && (b === 0 || b === 168)) return false; if (a === 192 && b === 88 && c === 99) return false; if (a === 198 && (b === 18 || b === 19 || b === 51)) return false; if (a === 203 && b === 0 && c === 113) return false; return true; } function normalizePattern(value, pattern, code) { if (typeof value !== "string" || !pattern.test(value)) { throw new TypeError(code); } return value; } function normalizeDisplayText(value, maxLength, code) { if (typeof value !== "string") throw new TypeError(code); const normalized = value.trim(); if (normalized.length < 1 || normalized.length > maxLength) { throw new TypeError(code); } if (/\u0000|[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(normalized)) { throw new TypeError(code); } return normalized; } function normalizeOptionalTimestamp(value) { if (value == null || value === "") return null; if (typeof value !== "string" || !isoTimestampPattern.test(value)) { throw new TypeError("device_enrollment_expires_at_invalid"); } const parsed = new Date(value); if (!Number.isFinite(parsed.getTime()) || parsed.toISOString() !== value) { throw new TypeError("device_enrollment_expires_at_invalid"); } return value; } function normalizeEnum(value, allowed, code) { if (typeof value !== "string" || !allowed.has(value)) { throw new TypeError(code); } return value; } function assertPlainObject(value, code) { if (!value || typeof value !== "object" || Array.isArray(value)) { throw new TypeError(code); } } function assertAllowedKeys(input, allowed) { const allowedSet = new Set(allowed); for (const key of Object.keys(input)) { if (!allowedSet.has(key)) { throw new TypeError(`device_management_command_field_unexpected:${key}`); } } } function domainError(code, statusCode) { const error = new Error(code); error.statusCode = statusCode; return error; }