/** * @license * Copyright 2022-2026 Matter.js Authors * SPDX-License-Identifier: Apache-2.0 */ import { PersistedFileDesignator } from "#bdx/PersistedFileDesignator.js"; import { ScopedStorage } from "#bdx/ScopedStorage.js"; import { DclErrorCodes } from "#dcl/DclRestApiTypes.js"; import { asError, BlobStorageDriver, Construction, Crypto, Diagnostic, Environment, hashAlgorithmForId, ImplementationError, Logger, MatterError, Minutes, StorageError, StorageService, } from "@matter/general"; import { DeviceSoftwareVersionModelDclSchema, VendorId } from "@matter/types"; import { OtaImageReader } from "../ota/OtaImageReader.js"; import { DclClient, MatterDclError, MatterDclResponseError } from "./DclClient.js"; import { DclConfig } from "./DclConfig.js"; const logger = Logger.get("DclOtaUpdateService"); /** Error thrown when OTA update check or download fails */ export class OtaUpdateError extends MatterError { constructor(message: string, options?: ErrorOptions) { super(message, options); } } export type OtaUpdateSource = "local" | "dcl-prod" | "dcl-test"; export type OtaStorageMode = "prod" | "test" | "local"; export interface DeviceSoftwareVersionModelDclSchemaWithSource extends DeviceSoftwareVersionModelDclSchema { source: OtaUpdateSource; } /** * Update information returned by checkForUpdate. * This is an alias for the DCL schema to provide better semantic meaning. */ export type OtaUpdateInfo = DeviceSoftwareVersionModelDclSchemaWithSource; const OTA_DOWNLOAD_TIMEOUT = Minutes(5); const OTA_FILENAME_REGEX = /^[0-9a-f]+[./][0-9a-f]+[./](?:prod|test|local)[./]\d+$/i; /** * Root context for the metadata of stored images, beside the image contexts. It mirrors their layout, so an image and * its metadata share context path and key. */ const OTA_METADATA_CONTEXT = "meta"; interface StoredImageMetadata { specificationVersion?: number; } function isSpecificationVersion(value: unknown): value is number { return typeof value === "number" && Number.isInteger(value) && value > 0 && value <= 0xffff_ffff; } /** * Service to query and manage OTA updates from the Distributed Compliance Ledger (DCL), but also allows to inject own * OTA update info from streams or files. The service is designed as a singleton within an Environment and is shared * across multiple nodes. This service is mainly relevant for controllers. * * The service checks the DCL for available software updates for Matter devices and can download and validate OTA * images. Production and test DCL instances are supported, with separate file storage for each. */ export class DclOtaUpdateService { readonly #construction: Construction; readonly #crypto: Crypto; readonly #options?: DclOtaUpdateService.Options; #blobDriver?: BlobStorageDriver; #closeBlobStorage?: () => Promise; #storage?: ScopedStorage; #closed = false; get construction() { return this.#construction; } /** Whether the service runs {@link DclOtaUpdateService.Options.offline}. */ get offline() { return this.#options?.offline ?? false; } constructor(environment: Environment, options?: DclOtaUpdateService.Options) { environment.root.set(DclOtaUpdateService, this); this.#crypto = environment.get(Crypto); this.#options = options; logger.info( "Initialize OTAUpdateService", Diagnostic.dict({ prod: options?.productionDclConfig?.url ?? DclConfig.production.url, test: options?.testDclConfig?.url ?? DclConfig.test.url, flags: Diagnostic.asFlags({ offline: options?.offline }), }), ); // The construction is async and will be enforced when needed this.#construction = Construction(this, async () => { const blobHandle = await environment.get(StorageService).openBlobStorage("ota"); this.#blobDriver = blobHandle.driver; this.#closeBlobStorage = blobHandle.close; this.#storage = new ScopedStorage(this.#blobDriver, ["bin"], "ota"); await this.#migrateStorage(); }); } get storage() { this.construction.assert(); return this.#storage!; } async close() { this.#closed = true; await this.#construction.close(async () => { await this.#closeBlobStorage?.(); }); } async #migrateStorage() { const blobDriver = this.#blobDriver!; const baseContexts = this.#storage!.baseContexts; for (const vendorHex of await blobDriver.contexts(baseContexts)) { const vendorContexts = [...baseContexts, vendorHex]; for (const productHex of await blobDriver.contexts(vendorContexts)) { const productContexts = [...vendorContexts, productHex]; const keys = await blobDriver.keys(productContexts); for (const key of keys) { if (key !== "prod" && key !== "test") { continue; // Not an old-format key } try { // Read the old file header to extract the software version const headerBlob = await blobDriver.openBlob(productContexts, key); const headerReader = headerBlob.stream().getReader(); const header = await OtaImageReader.header(headerReader); await headerReader.cancel(); const versionKey = header.softwareVersion.toString(); // Copy to new location: mode sub-context + version key const modeContexts = [...productContexts, key]; const copyBlob = await blobDriver.openBlob(productContexts, key); await blobDriver.writeBlobFromStream(modeContexts, versionKey, copyBlob.stream()); // Delete old bare key await blobDriver.delete(productContexts, key); logger.info( `Migrated OTA storage: ${vendorHex}.${productHex}.${key} -> ${vendorHex}.${productHex}.${key}.${versionKey}`, ); } catch (error) { logger.warn( `Failed to migrate OTA file ${vendorHex}.${productHex}.${key}, deleting corrupt entry:`, error, ); try { await blobDriver.delete(productContexts, key); } catch { // Ignore cleanup errors } } } } } } async #queryDclForUpdate(options: { vendorId: number; productId: number; currentSoftwareVersion: number; includeStoredUpdates?: boolean; isProduction: boolean; targetSoftwareVersion?: number; }) { if (this.#options?.offline) { return; } const { vendorId, productId, currentSoftwareVersion, isProduction, targetSoftwareVersion } = options; const config = isProduction ? (this.#options?.productionDclConfig ?? DclConfig.production) : (this.#options?.testDclConfig ?? DclConfig.test); const dclClient = new DclClient(config); const dclLogStr = isProduction ? "Prod-DCL" : "Test-DCL"; const diagnosticInfo = { vid: vendorId, pid: productId, prod: isProduction, current: currentSoftwareVersion, }; try { // If a specific target version is requested, check only that version if (targetSoftwareVersion !== undefined) { logger.debug( `Checking update in ${dclLogStr} for specific version`, Diagnostic.dict({ ...diagnosticInfo, target: targetSoftwareVersion, }), ); return await this.#checkSpecificVersion( dclClient, vendorId, productId, targetSoftwareVersion, currentSoftwareVersion, ); } // Otherwise, get all available versions and find the best applicable one const softwareVersions = await dclClient.fetchModelVersionsByVidPid(vendorId, productId); // Filter for versions higher than the current, sort to check the highest version number first const newerVersions = softwareVersions .filter(version => version > currentSoftwareVersion) .sort((a, b) => b - a); if (newerVersions.length === 0) { logger.debug(`No newer versions available in ${dclLogStr}`, Diagnostic.dict(diagnosticInfo)); return; } logger.debug( `Found ${newerVersions.length} newer version(s) in ${dclLogStr}`, Diagnostic.dict(diagnosticInfo), ); // Check each version starting from highest, find the first applicable one for (const version of newerVersions) { if (this.#closed) { return; } try { const updateInfo = await this.#checkSpecificVersion( dclClient, vendorId, productId, version, currentSoftwareVersion, ); if (updateInfo !== undefined) { logger.info( `Update available in ${dclLogStr}`, Diagnostic.dict({ new: version, ...diagnosticInfo }), ); return updateInfo; } } catch (error) { MatterDclError.accept(error); logger.info(`Failed to check for update for VID: ${vendorId}, PID: ${productId}: ${error.message}`); } } logger.debug(`No applicable updates found in ${dclLogStr}`, Diagnostic.dict(diagnosticInfo)); } catch (error) { MatterDclError.accept(error); if (error instanceof MatterDclResponseError && error.response.code === DclErrorCodes.NotFound) { logger.debug(`No applicable updates found in ${dclLogStr}`, Diagnostic.dict(diagnosticInfo)); } else { logger.info(`Failed to check for updates for VID: ${vendorId}, PID: ${productId}: ${error.message}`); } } } /** * Check DCL for available software updates for a device, defined by its vendor ID, product ID, and current * software version. If a target software version is provided, only that version is checked for applicability and * ignoring other newer versions. * If isProduction flag is specified, it is exactly used to find updates. Leave that flag undefined to find both * test and production updates. * When the service is {@link DclOtaUpdateService.Options.offline} the DCL is not asked, so only stored updates * (`includeStoredUpdates`) can be found. */ async checkForUpdate(options: { vendorId: number; productId: number; currentSoftwareVersion: number; includeStoredUpdates?: boolean; isProduction?: boolean; targetSoftwareVersion?: number; }): Promise { const { vendorId, productId, currentSoftwareVersion, includeStoredUpdates = false, isProduction, targetSoftwareVersion, } = options; const foundUpdates = new Array(); // Only stored test-mode files are gated on the test DCL being enabled; prod and local entries always // pass through, so a test-only caller still sees them as valid upgrade targets. if (includeStoredUpdates) { const localUpdates = await this.find({ vendorId, productId, currentVersion: currentSoftwareVersion, }); // Check each stored entry for applicability (highest version first via reverse iteration) for (let i = localUpdates.length - 1; i >= 0; i--) { const entry = localUpdates[i]; if (isProduction === true && entry.mode === "test") continue; const localUpdate: DeviceSoftwareVersionModelDclSchemaWithSource = { ...entry, vid: VendorId(vendorId), pid: productId, cdVersionNumber: 0, softwareVersionValid: true, schemaVersion: 1, minApplicableSoftwareVersion: entry.minApplicableSoftwareVersion ?? 0, maxApplicableSoftwareVersion: entry.maxApplicableSoftwareVersion ?? entry.softwareVersion - 1, source: entry.mode === "prod" ? "dcl-prod" : entry.mode === "test" ? "dcl-test" : "local", }; if ( localUpdate.softwareVersion > currentSoftwareVersion && currentSoftwareVersion >= localUpdate.minApplicableSoftwareVersion && currentSoftwareVersion <= localUpdate.maxApplicableSoftwareVersion ) { logger.debug(`Found applicable local update`, Diagnostic.dict(localUpdate)); if (targetSoftwareVersion !== undefined && localUpdate.softwareVersion === targetSoftwareVersion) { return localUpdate; } foundUpdates.push(localUpdate); } } } // Check for Prod DCL updates if (isProduction !== false && !this.#closed) { const prodUpdate = await this.#queryDclForUpdate({ ...options, isProduction: true }); if (prodUpdate !== undefined) { const updateEntry: DeviceSoftwareVersionModelDclSchemaWithSource = { ...prodUpdate, source: "dcl-prod", }; if (targetSoftwareVersion !== undefined && updateEntry.softwareVersion === targetSoftwareVersion) { return updateEntry; } foundUpdates.push(updateEntry); } } // Check for Test DCL updates if (isProduction !== true && !this.#closed) { const testUpdate = await this.#queryDclForUpdate({ ...options, isProduction: false }); if (testUpdate !== undefined) { const updateEntry: DeviceSoftwareVersionModelDclSchemaWithSource = { ...testUpdate, source: "dcl-test", }; if (targetSoftwareVersion !== undefined && updateEntry.softwareVersion === targetSoftwareVersion) { return updateEntry; } foundUpdates.push(updateEntry); } } // The logic above would have found the update already when it would match that version, so no update found if (targetSoftwareVersion !== undefined || !foundUpdates.length) { return; } // Sort for versions, highest version number first foundUpdates.sort((a, b) => b.softwareVersion - a.softwareVersion); return foundUpdates[0]; } async #verifyUpdate(updateInfo: OtaUpdateInfo, fileDesignator: PersistedFileDesignator) { const { otaFileSize, softwareVersion, vid, pid } = updateInfo; const storedBlob = await fileDesignator.openBlob(); const reader = storedBlob.stream().getReader(); // Validate with full checksum if DCL provided one let checksumOptions; if (updateInfo.otaChecksum) { const checksumType = hashAlgorithmForId(updateInfo.otaChecksumType ?? 1); if (checksumType === undefined) { throw new OtaUpdateError(`Unsupported OTA checksum type: ${updateInfo.otaChecksumType}`); } checksumOptions = { calculateFullChecksum: true, checksumType, expectedChecksum: updateInfo.otaChecksum, }; } const header = await OtaImageReader.file(reader, this.#crypto, otaFileSize, checksumOptions); // Verify that the header matches the expected update if (header.vendorId !== vid) { throw new OtaUpdateError(`OTA image vendor ID mismatch: expected ${vid}, got ${header.vendorId}`); } if (header.productId !== pid) { throw new OtaUpdateError(`OTA image product ID mismatch: expected ${pid}, got ${header.productId}`); } if (header.softwareVersion !== softwareVersion) { throw new OtaUpdateError( `OTA image software version mismatch: expected ${softwareVersion}, got ${header.softwareVersion}`, ); } } /** * Location of the metadata for an image, given by its filename or by its image contexts and key. */ /** * Validate a stored image against the update info. A storage or I/O error makes the image "unreadable", not * "invalid", because it says nothing about the image content. */ async #checkStoredImage( updateInfo: OtaUpdateInfo, fileDesignator: PersistedFileDesignator, ): Promise<{ kind: "valid" } | { kind: "invalid" } | { kind: "unreadable"; cause: unknown }> { try { await this.#verifyUpdate(updateInfo, fileDesignator); return { kind: "valid" }; } catch (error) { if (!(error instanceof MatterError) || error instanceof StorageError) { logger.info( `Cannot read stored OTA image ${fileDesignator.text} to validate it`, Diagnostic.errorMessage(asError(error)), ); return { kind: "unreadable", cause: error }; } logger.info(`Existing OTA image ${fileDesignator.text} failed validation`, Diagnostic.errorMessage(error)); return { kind: "invalid" }; } } #metadataLocation(filenameOrContexts: string | readonly string[], key?: string) { let imageContexts: readonly string[]; if (typeof filenameOrContexts === "string") { const parts = filenameOrContexts.split("."); key = parts.pop(); imageContexts = [...this.#storage!.baseContexts, ...parts]; } else { imageContexts = filenameOrContexts; } return { contexts: [OTA_METADATA_CONTEXT, ...imageContexts.slice(this.#storage!.baseContexts.length)], key: key ?? "", }; } /** * Record the metadata of a stored image; a value that is not set removes it. The metadata is optional, so a * failure is logged and does not fail the store. */ async #recordMetadata(filename: string, metadata: StoredImageMetadata) { const { specificationVersion } = metadata; try { if (specificationVersion === undefined || !isSpecificationVersion(specificationVersion)) { if (specificationVersion !== undefined) { logger.warn(`Not storing invalid specification version ${specificationVersion} for ${filename}`); } await this.#deleteMetadata(filename); return; } const { contexts, key } = this.#metadataLocation(filename); await this.#blobDriver!.writeBlobFromStream( contexts, key, new Blob([JSON.stringify({ specificationVersion })]).stream(), ); } catch (error) { logger.warn(`Failed to store metadata of OTA image ${filename}:`, Diagnostic.errorMessage(asError(error))); } } /** * Read the metadata of a stored image. Unreadable or invalid metadata is removed, so it is reported only once. */ async #readMetadata(imageContexts: readonly string[], key: string): Promise { const { contexts } = this.#metadataLocation(imageContexts, key); const blobDriver = this.#blobDriver!; const name = [...contexts, key].join("."); try { if (!(await blobDriver.has(contexts, key))) { return {}; } const { specificationVersion } = JSON.parse(await (await blobDriver.openBlob(contexts, key)).text()); if (isSpecificationVersion(specificationVersion)) { return { specificationVersion }; } logger.warn(`Removing invalid metadata of stored OTA image ${name}`); } catch (error) { logger.warn( `Removing unreadable metadata of stored OTA image ${name}:`, Diagnostic.errorMessage(asError(error)), ); } try { await blobDriver.delete(contexts, key); } catch (error) { logger.warn( `Failed to remove metadata of stored OTA image ${name}:`, Diagnostic.errorMessage(asError(error)), ); } return {}; } async #deleteMetadata(filenameOrContexts: string | readonly string[], key?: string) { const location = this.#metadataLocation(filenameOrContexts, key); const blobDriver = this.#blobDriver!; if (await blobDriver.has(location.contexts, location.key)) { await blobDriver.delete(location.contexts, location.key); } } #fileName(vid: number, pid: number, mode: OtaStorageMode, softwareVersion: number) { return `${vid.toString(16)}.${pid.toString(16)}.${mode}.${softwareVersion}`; } /** * Store an OTA update image from a ReadableStream into persistent storage. */ async store( stream: ReadableStream, updateInfo: OtaUpdateInfo, // TODO: Change default to "local" on next breaking release mode: boolean | OtaStorageMode = true, ) { if (this.#storage === undefined) { await this.construction; } const storage = this.#storage!; if (typeof mode === "boolean") { mode = mode ? "prod" : "test"; } const { softwareVersion, softwareVersionString, vid, pid } = updateInfo; const filename = this.#fileName(vid, pid, mode, softwareVersion); const fileDesignator = new PersistedFileDesignator(filename, storage); const diagnosticInfo = { filename, vid, pid, v: `${softwareVersion} (${softwareVersionString})`, mode, }; try { // Write to storage using streaming via PersistedFileDesignator await fileDesignator.writeFromStream(stream); // Read back from storage and validate (including full file checksum if provided by DCL) await this.#verifyUpdate(updateInfo, fileDesignator); await this.#recordMetadata(filename, { specificationVersion: updateInfo.specificationVersion }); logger.debug(`Stored OTA image`, Diagnostic.dict(diagnosticInfo)); return fileDesignator; } catch (error) { // Clean up on error try { await fileDesignator.delete(); } catch { // Ignore cleanup errors } try { await this.#deleteMetadata(filename); } catch { // Ignore cleanup errors } throw error; } } /** * Download and validate an OTA update image from a HTTP pr HTTPS server. * * If a file with the same vendor ID, product ID, and production mode already exists * and passes validation, it will be reused instead of downloading again, unless force is true. * * Production and test files are stored separately to avoid conflicts. * * Returns a PersistedFileDesignator for the validated OTA image * * A stored image that fails validation is removed. Online, a stored image that cannot be read is replaced by a * download as well. * * @throws {OtaUpdateError} if the image is neither stored and valid nor downloadable. When the service is * {@link DclOtaUpdateService.Options.offline} it throws instead of downloading: after a stored image that fails * validation was removed, when none is stored, when the stored image cannot be read (it is kept) and with * `force` (the stored image is kept) */ async downloadUpdate(updateInfo: OtaUpdateInfo, force = false, timeout = OTA_DOWNLOAD_TIMEOUT) { if (this.#storage === undefined) { await this.construction; } const storage = this.#storage!; const { otaUrl, softwareVersion, softwareVersionString, vid, pid, source } = updateInfo; const mode: OtaStorageMode = source === "dcl-prod" ? "prod" : source === "dcl-test" ? "test" : "local"; const diagnosticInfo = { vid, pid, v: `${softwareVersion} (${softwareVersionString})`, mode, }; const filename = this.#fileName(vid, pid, mode, softwareVersion); const fileDesignator = new PersistedFileDesignator(filename, storage); const exists = await fileDesignator.exists(); const check = exists && !force ? await this.#checkStoredImage(updateInfo, fileDesignator) : undefined; if (check?.kind === "valid") { logger.info(`Existing OTA image validated successfully`, Diagnostic.dict(diagnosticInfo)); if (updateInfo.specificationVersion !== undefined) { await this.#recordMetadata(filename, { specificationVersion: updateInfo.specificationVersion }); } return fileDesignator; } const offline = this.#options?.offline ?? false; // Offline nothing can replace the image, so only one shown to be invalid is removed const keepStored = exists && offline && check?.kind !== "invalid"; if (exists && !keepStored) { await fileDesignator.delete(); await this.#deleteMetadata(filename); } if (offline) { if (check?.kind === "unreadable") { throw new OtaUpdateError( `Cannot read stored OTA image ${filename} (${softwareVersionString}) to validate it and the service is offline; the stored image is kept`, { cause: check.cause }, ); } throw new OtaUpdateError( keepStored ? `Cannot force a download of OTA image ${filename} (${softwareVersionString}) while the service is offline; the stored image is kept` : `No valid OTA image ${filename} (${softwareVersionString}) is stored and the service is offline, so none is downloaded`, ); } if (!otaUrl?.trim()) { throw new OtaUpdateError("No OTA URL provided in update info"); } // Validate protocol let url: URL; try { url = new URL(otaUrl); } catch { throw new OtaUpdateError(`Invalid OTA URL: ${otaUrl}`); } const protocol = url.protocol.toLowerCase(); if (protocol !== "https:" && protocol !== "http:") { throw new OtaUpdateError( `Unsupported protocol "${protocol}" in OTA URL. Only "https:", "http:" are supported`, ); } logger.info(`Downloading OTA image from ${otaUrl}`, Diagnostic.dict(diagnosticInfo)); try { // Download or load the OTA image const response = await fetch(otaUrl, { method: "GET", signal: AbortSignal.timeout(timeout), }); if (!response.ok) { throw new OtaUpdateError(`Failed to download OTA image: ${response.status} ${response.statusText}`); } if (!response.body) { throw new OtaUpdateError("No response body received"); } return await this.store(response.body, updateInfo, mode); } catch (error) { MatterError.reject(error); const otaError = new OtaUpdateError(`Failed to download OTA image from ${otaUrl}`); otaError.cause = error; throw otaError; } } /** * Check a specific software version for applicability. * * @param dclClient - DCL client to use for fetching * @param vendorId - Vendor ID of the device * @param productId - Product ID of the device * @param softwareVersion - The specific version to check * @param currentVersion - Current software version of the device * @returns Update information if the version is applicable, undefined otherwise */ async #checkSpecificVersion( dclClient: DclClient, vendorId: number, productId: number, softwareVersion: number, currentVersion: number, ) { const versionInfo = await dclClient.fetchModelVersionByVidPidSoftwareVersion( vendorId, productId, softwareVersion, ); // Verify that the returned version matches the requested version if (versionInfo.softwareVersion !== softwareVersion) { throw new OtaUpdateError( `Version mismatch: requested ${softwareVersion}, but DCL returned ${versionInfo.softwareVersion}`, ); } // Check if this version is applicable if (this.#isVersionApplicable(versionInfo, currentVersion)) { logger.debug( `Found applicable update: version ${softwareVersion} (${versionInfo.softwareVersionString}) for current version ${currentVersion}`, ); return { ...versionInfo, specificationVersion: (await this.#specificationVersionOf(dclClient, vendorId, productId, softwareVersion)) ?? versionInfo.specificationVersion, }; } logger.debug( `Version ${softwareVersion} is not applicable`, Diagnostic.dict({ valid: versionInfo.softwareVersionValid, url: !!versionInfo.otaUrl, min: versionInfo.minApplicableSoftwareVersion, max: versionInfo.maxApplicableSoftwareVersion, }), ); } /** * Read the specification version of a software version from its compliance record. Matter 1.6.1 moves the field * there from the software version record, which the DCL no longer fills. A failed lookup leaves it unknown and * does not fail the update check. */ async #specificationVersionOf(dclClient: DclClient, vendorId: number, productId: number, softwareVersion: number) { try { const compliance = await dclClient.fetchComplianceInfo(vendorId, productId, softwareVersion, "matter"); return compliance.specificationVersion; } catch (error) { MatterDclError.accept(error); logger.debug( `No specification version from compliance info for VID: ${vendorId}, PID: ${productId}, version ${softwareVersion}: ${error.message}`, ); } } /** * Check if a software version is applicable for the current device version. */ #isVersionApplicable(versionInfo: DeviceSoftwareVersionModelDclSchema, currentVersion: number): boolean { // Must be marked as valid if (!versionInfo.softwareVersionValid) { return false; } // Must have an OTA URL if (!versionInfo.otaUrl?.trim()) { return false; } // DCL OTA URLs must use HTTPS protocol for security if (!versionInfo.otaUrl.toLowerCase().startsWith("https://")) { logger.warn(`Invalid OTA URL from DCL: "${versionInfo.otaUrl}" - must use https:// protocol`); return false; } // The current version must be within the applicable range if specified if ( versionInfo.minApplicableSoftwareVersion !== undefined && currentVersion < versionInfo.minApplicableSoftwareVersion ) { return false; } if ( versionInfo.maxApplicableSoftwareVersion !== undefined && currentVersion > versionInfo.maxApplicableSoftwareVersion ) { return false; } return true; } /** * Create OtaUpdateInfo from an OTA image stream. * * This method reads and validates an OTA image from a ReadableStream and creates an OtaUpdateInfo * structure. This is useful for providing OTA updates from local files or any stream source. * * The OTA image header contains most required information. However, some DCL-specific * fields are not present in the OTA header and must be provided via options or use defaults: * - cdVersionNumber: Certificate Declaration version (defaults to 1) * - softwareVersionValid: Validity flag (defaults to true) * - schemaVersion: DCL schema version (defaults to 0) * - minApplicableSoftwareVersion: If not in header, defaults to 0 (all versions) * - maxApplicableSoftwareVersion: If not in header, defaults to current version minus 1 * - specificationVersion: Not in the OTA header; stored with the image when provided * * @param stream - ReadableStream of the OTA image * @param otaUrl - URL to use for the OTA file (should be file:// for local files or https:// for remote) * @param options - Optional parameters for DCL-specific fields not in OTA header * @returns OtaUpdateInfo with stream data and header information */ async updateInfoFromStream( stream: ReadableStream, otaUrl: string, options?: { /** Certificate Declaration version number. Defaults to 1. */ cdVersionNumber?: number; /** Whether this version is valid. Defaults to true. */ softwareVersionValid?: boolean; /** DCL schema version. Defaults to 0. */ schemaVersion?: number; /** * Minimum applicable software version. If not provided and not in OTA header, * defaults to 0 (applicable to all versions). */ minApplicableSoftwareVersion?: number; /** * Maximum applicable software version. If not provided and not in OTA header, * defaults to current version (only applicable to current version and below). */ maxApplicableSoftwareVersion?: number; /** Matter specification version the image implements, stored with the image. */ specificationVersion?: number; }, ) { // Read and validate the OTA image header from stream const reader = stream.getReader(); const header = await OtaImageReader.header(reader); // Build OtaUpdateInfo from header and options const updateInfo: OtaUpdateInfo = { vid: VendorId(header.vendorId), pid: header.productId, softwareVersion: header.softwareVersion, softwareVersionString: header.softwareVersionString, cdVersionNumber: options?.cdVersionNumber ?? 1, softwareVersionValid: options?.softwareVersionValid ?? true, otaUrl, // Use header values if present, otherwise use provided options or defaults minApplicableSoftwareVersion: header.minApplicableSoftwareVersion ?? options?.minApplicableSoftwareVersion ?? 0, maxApplicableSoftwareVersion: header.maxApplicableSoftwareVersion ?? options?.maxApplicableSoftwareVersion ?? header.softwareVersion - 1, releaseNotesUrl: header.releaseNotesUrl, specificationVersion: options?.specificationVersion, schemaVersion: options?.schemaVersion ?? 0, source: "local", }; logger.debug( `OTA update info from stream`, Diagnostic.dict({ vid: header.vendorId, pid: header.productId, v: `${header.softwareVersion} (${header.softwareVersionString})`, }), ); return updateInfo; } /** * Create OtaUpdateInfo from a remote OTA image file URL. * * This method fetches and validates a remote OTA image file (via HTTPS) and creates an OtaUpdateInfo * structure that can be used with downloadUpdate(). For local files, use updateInfoFromStream() instead. * * The OTA image header contains most required information. However, some DCL-specific * fields are not present in the OTA header and must be provided via options or use defaults: * - cdVersionNumber: Certificate Declaration version (defaults to 1) * - softwareVersionValid: Validity flag (defaults to true) * - schemaVersion: DCL schema version (defaults to 0) * - minApplicableSoftwareVersion: If not in header, defaults to 0 (all versions) * - maxApplicableSoftwareVersion: If not in header, defaults to current version * - specificationVersion: Not in the OTA header; stored with the image when provided * * @param fileUrl - HTTPS URL to the OTA image file * @param options - Optional parameters for DCL-specific fields not in OTA header * @returns OtaUpdateInfo with file URL and header data * @throws {OtaUpdateError} if the image cannot be read, including when the service is * {@link DclOtaUpdateService.Options.offline} */ async createUpdateInfoFromFile( fileUrl: string, options?: { /** Certificate Declaration version number. Defaults to 1. */ cdVersionNumber?: number; /** Whether this version is valid. Defaults to true. */ softwareVersionValid?: boolean; /** DCL schema version. Defaults to 0. */ schemaVersion?: number; /** * Minimum applicable software version. If not provided and not in OTA header, * defaults to 0 (applicable to all versions). */ minApplicableSoftwareVersion?: number; /** * Maximum applicable software version. If not provided and not in OTA header, * defaults to current version (only applicable to current version and below). */ maxApplicableSoftwareVersion?: number; /** Matter specification version the image implements, stored with the image. */ specificationVersion?: number; }, ) { const fileProtocol = fileUrl.split(":")[0].toLowerCase(); // Validate URL is HTTPS if (fileProtocol !== "https" && fileProtocol !== "http") { throw new OtaUpdateError( `Only HTTP(S) URLs are supported. For local files, use updateInfoFromStream() instead.`, ); } if (this.#options?.offline) { throw new OtaUpdateError( `Cannot read OTA image from ${fileUrl}: the service is offline, use updateInfoFromStream() instead`, ); } try { // Fetch and read the OTA image const response = await fetch(fileUrl, { method: "GET" }); if (!response.ok) { throw new OtaUpdateError(`Failed to fetch OTA image: ${response.status} ${response.statusText}`); } if (!response.body) { throw new OtaUpdateError("No response body received"); } // Use the stream-based method return await this.updateInfoFromStream(response.body, fileUrl, options); } catch (error) { MatterError.reject(error); const otaError = new OtaUpdateError(`Failed to read OTA image from ${fileUrl}`); otaError.cause = error; throw otaError; } } /** * Find downloaded OTA updates in storage. * * This method scans the OTA storage for downloaded update files and returns * information about them. Files can be filtered by vendor ID, product ID, * and production/test mode. * * @param options - Optional filter criteria * @param options.vendorId - Filter by vendor ID * @param options.productId - Filter by product ID (requires vendorId) * @param options.isProduction - Filter by production (true) or test (false) mode * @returns Array of downloaded update information */ async find(options: DclOtaUpdateService.FindOptions = {}) { if (this.#storage === undefined) { await this.construction; } const results = await this.#findEntries(this.#storage!.baseContexts, options); // Sort by vendor ID, product ID, mode, and version const modeOrder: Record = { prod: 0, test: 1, local: 2 }; results.sort((a, b) => { const modeDiff = (modeOrder[a.mode] ?? 99) - (modeOrder[b.mode] ?? 99); if (modeDiff !== 0) return modeDiff; if (a.vendorId !== b.vendorId) return a.vendorId - b.vendorId; if (a.productId !== b.productId) return a.productId - b.productId; return a.softwareVersion - b.softwareVersion; }); return results; } async #findEntries( baseContexts: readonly string[], options: DclOtaUpdateService.FindOptions, ): Promise { const blobDriver = this.#blobDriver!; const { vendorId } = options; if (vendorId !== undefined) { const vendorContexts = [...baseContexts, vendorId.toString(16)]; const vendorEntries = await this.#findVendorEntries(vendorContexts, options); return vendorEntries.map(entry => ({ ...entry, vendorId, filename: this.#fileName(vendorId, entry.productId, entry.mode, entry.softwareVersion), })); } const result = new Array(); for (const vendorIdHex of await blobDriver.contexts(baseContexts)) { const vendorId = parseInt(vendorIdHex, 16); const vendorContexts = [...baseContexts, vendorIdHex]; const vendorEntries = await this.#findVendorEntries(vendorContexts, options); result.push( ...vendorEntries.map(entry => ({ ...entry, vendorId, filename: this.#fileName(vendorId, entry.productId, entry.mode, entry.softwareVersion), })), ); } return result; } async #findVendorEntries(vendorContexts: string[], options: DclOtaUpdateService.FindOptions) { const blobDriver = this.#blobDriver!; const { productId } = options; if (productId !== undefined) { const productContexts = [...vendorContexts, productId.toString(16)]; const productEntries = await this.#findVendorProductEntries(productContexts, options); return productEntries.map(entry => ({ ...entry, productId })); } const result = new Array>(); for (const productIdHex of await blobDriver.contexts(vendorContexts)) { const productId = parseInt(productIdHex, 16); const productContexts = [...vendorContexts, productIdHex]; const productEntries = await this.#findVendorProductEntries(productContexts, options); result.push(...productEntries.map(entry => ({ ...entry, productId }))); } return result; } async #findVendorProductEntries(productContexts: string[], options: DclOtaUpdateService.FindOptions) { const blobDriver = this.#blobDriver!; const { isProduction, mode: filterMode } = options; const result = new Array>(); // New format: enumerate mode sub-contexts const modeSubContexts = await blobDriver.contexts(productContexts); const validModes: OtaStorageMode[] = ["prod", "test", "local"]; for (const modeStr of modeSubContexts) { if (!validModes.includes(modeStr as OtaStorageMode)) { continue; } const mode = modeStr as OtaStorageMode; // Apply mode/isProduction filters if (filterMode !== undefined && filterMode !== mode) { continue; } if (filterMode === undefined && isProduction !== undefined) { if (isProduction === true && mode !== "prod") continue; if (isProduction === false && mode === "prod") continue; } const modeContexts = [...productContexts, modeStr]; const versionKeys = await blobDriver.keys(modeContexts); for (const versionKey of versionKeys) { const fileDesignator = new PersistedFileDesignator(versionKey, blobDriver, modeContexts); const entry = await this.#checkEntry(fileDesignator, options); if (entry !== undefined) { const { specificationVersion } = await this.#readMetadata(modeContexts, versionKey); result.push({ ...entry, mode, specificationVersion, }); } } } return result; } async #checkEntry(fileDesignator: PersistedFileDesignator, options: DclOtaUpdateService.FindOptions) { try { // Read header to get software version and size const blob = await fileDesignator.openBlob(); const reader = blob.stream().getReader(); const header = await OtaImageReader.header(reader); await reader.cancel(); const { currentVersion } = options; if (currentVersion !== undefined) { // The current version must be within the applicable range if specified if ( header.minApplicableSoftwareVersion !== undefined && currentVersion < header.minApplicableSoftwareVersion ) { return; } if ( header.maxApplicableSoftwareVersion !== undefined && currentVersion > header.maxApplicableSoftwareVersion ) { return; } } return { softwareVersion: header.softwareVersion, softwareVersionString: header.softwareVersionString, minApplicableSoftwareVersion: header.minApplicableSoftwareVersion, maxApplicableSoftwareVersion: header.maxApplicableSoftwareVersion, size: blob.size, }; } catch (error) { logger.warn(`Failed to read OTA file ${fileDesignator.text}:`, Diagnostic.errorMessage(asError(error))); } } /** Get a PersistedFileDesignator for a stored OTA update file by filename. */ async fileDesignatorForUpdate(filename: string) { if (!OTA_FILENAME_REGEX.test(filename)) { throw new ImplementationError(`Invalid OTA filename format: ${filename}`); } if (this.#storage === undefined) { await this.construction; } const fileDesignator = new PersistedFileDesignator(filename, this.#storage!); if (!(await fileDesignator.exists())) { throw new OtaUpdateError(`OTA file not found: ${filename}`); } return fileDesignator; } /** * Delete stored OTA update files. * * Can delete by specific filename or by vendor ID, product ID, and mode. * If only vendor ID is provided (no product ID), all files for that vendor are deleted. * * @param options - Deletion criteria * @param options.filename - Specific filename to delete (e.g. `fff1.8000.prod.3`) * @param options.vendorId - Vendor ID to filter files for deletion * @param options.productId - Product ID to filter files for deletion (optional, requires vendorId) * @param options.isProduction - (deprecated, use `mode` instead) production (true) or test (false) mode * @param options.mode - Storage mode: "prod", "test", or "local" * @returns Number of files deleted */ async delete(options: { filename?: string; vendorId?: number; productId?: number; /** @deprecated Use mode instead */ isProduction?: boolean; mode?: OtaStorageMode; }) { if (this.#storage === undefined) { await this.construction; } const storage = this.#storage!; const { vendorId, productId, isProduction } = options; let { filename, mode } = options; // Backward compat: derive mode from boolean if (mode === undefined && isProduction !== undefined) { mode = isProduction ? "prod" : "test"; } if (filename !== undefined) { // Delete a specific file by name — fileDesignatorForUpdate expects the new filename format with a version suffix try { const fileDesignator = await this.fileDesignatorForUpdate(filename); await fileDesignator.delete(); await this.#deleteMetadata(filename); } catch (error) { OtaUpdateError.accept(error); // Ignore not found errors return 0; } logger.info(`Deleted OTA file: ${filename}`); return 1; } const blobDriver = this.#blobDriver!; const baseContexts = storage.baseContexts; if (vendorId !== undefined && productId !== undefined && mode !== undefined) { // Delete all versions for this vid/pid/mode const vendorHex = vendorId.toString(16); const productHex = productId.toString(16); const modeContexts = [...baseContexts, vendorHex, productHex, mode]; const versionKeys = await blobDriver.keys(modeContexts); let deletedCount = 0; for (const versionKey of versionKeys) { const fd = new PersistedFileDesignator(versionKey, blobDriver, modeContexts); await fd.delete(); await this.#deleteMetadata(modeContexts, versionKey); deletedCount++; } if (deletedCount > 0) { logger.info(`Deleted ${deletedCount} OTA file(s) for ${vendorHex}.${productHex}.${mode}`); } return deletedCount; } if (vendorId === undefined) { throw new OtaUpdateError("Either filename or vendorId must be provided to delete files"); } // Delete all files for the vendor, optionally filtered by mode const vendorHex = vendorId.toString(16); const vendorContexts = [...baseContexts, vendorHex]; let deletedCount = 0; const validModes: OtaStorageMode[] = ["prod", "test", "local"]; const modesToDelete = mode !== undefined ? [mode] : validModes; for (const productKey of await blobDriver.contexts(vendorContexts)) { const productContexts = [...vendorContexts, productKey]; const modeSubContexts = await blobDriver.contexts(productContexts); for (const modeStr of modesToDelete) { if (modeSubContexts.includes(modeStr)) { const modeContexts = [...productContexts, modeStr]; for (const versionKey of await blobDriver.keys(modeContexts)) { const fd = new PersistedFileDesignator(versionKey, blobDriver, modeContexts); await fd.delete(); await this.#deleteMetadata(modeContexts, versionKey); deletedCount++; } } } } return deletedCount; } } export namespace DclOtaUpdateService { export interface Options { /** DCL config for production endpoint. Defaults to DclConfig.production. */ productionDclConfig?: DclConfig; /** DCL config for test endpoint. Defaults to DclConfig.test. */ testDclConfig?: DclConfig; /** * Reaches no network at all: the DCL is not asked for updates and no OTA image is downloaded. Update checks * find only images already in storage (with `includeStoredUpdates`). {@link DclOtaUpdateService.downloadUpdate} * returns a stored image that validates; a stored image that fails validation is removed as online, and the * call then fails with {@link OtaUpdateError}. When the stored image cannot be read, or with `force`, it fails * without touching the stored image, since it cannot be replaced. Reading an image from a URL fails with * {@link OtaUpdateError}. * * For a deployment with no route to the ledger, and for short-lived test processes that must not depend on * it. */ offline?: boolean; } export type OtaUpdateListEntry = { filename: string; vendorId: number; productId: number; softwareVersion: number; softwareVersionString: string; minApplicableSoftwareVersion?: number; maxApplicableSoftwareVersion?: number; mode: OtaStorageMode; size: number; /** Specification version recorded when the image was stored, if known. */ specificationVersion?: number; }; export interface FindOptions { vendorId?: number; productId?: number; isProduction?: boolean; mode?: OtaStorageMode; currentVersion?: number; } }