diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c90a1e..20eb78f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,14 @@ +## 0.0.4 + +* Switch to the official contentauth c2pa-android and c2pa-ios 0.0.9 releases (from the redaranj forks) +* Add `getRemoteUrl` and `isManifestEmbedded` to the reader API +* Add `addIngredientFromFile` to the builder, reading the ingredient natively instead of passing bytes through Dart +* Add a typed `C2paSettingsDefinition`, with `C2paSettings.fromDefinition` and `updateFromDefinition` +* Support `settingsSetValue` on iOS +* Align `PredefinedAction` with the C2PA spec action list, adding the font and watermark actions +* **Breaking:** remove `Action.aiGenerated`, `PredefinedAction.aiGenerated` and other non-spec actions; tag AI-generated content with `Action.created(sourceType: DigitalSourceType.trainedAlgorithmicMedia)` instead +* iOS returns `NOT_IMPLEMENTED_IOS` for the hashed-signing and key-import/CSR/hardware-enrollment calls, which are not yet available there + ## 0.0.3 * Fix Android OOM crashes in file-based signing by replacing readBytes()/ByteArrayStream with FileStream diff --git a/android/build.gradle b/android/build.gradle index 10c7e19..e034d9e 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -49,7 +49,8 @@ android { } dependencies { - api("com.github.redaranj:c2pa-android:0.0.9-beta.7") + api("com.github.contentauth:c2pa-android:0.0.9") + implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0") testImplementation("org.jetbrains.kotlin:kotlin-test") testImplementation("org.mockito:mockito-core:5.0.0") } diff --git a/android/src/main/kotlin/org/guardianproject/c2pa/C2paPlugin.kt b/android/src/main/kotlin/org/guardianproject/c2pa/C2paPlugin.kt index 259ff9b..8f61a59 100644 --- a/android/src/main/kotlin/org/guardianproject/c2pa/C2paPlugin.kt +++ b/android/src/main/kotlin/org/guardianproject/c2pa/C2paPlugin.kt @@ -52,6 +52,8 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonPrimitive class C2paPlugin : FlutterPlugin, MethodCallHandler { private lateinit var channel: MethodChannel @@ -94,6 +96,8 @@ class C2paPlugin : FlutterPlugin, MethodCallHandler { "readBytesDetailed" -> handleReadBytesDetailed(call, result) "extractResource" -> handleExtractResource(call, result) "readIngredientFile" -> handleReadIngredientFile(call, result) + "getRemoteUrl" -> handleGetRemoteUrl(call, result) + "isManifestEmbedded" -> handleIsManifestEmbedded(call, result) "getSupportedReadMimeTypes" -> handleGetSupportedReadMimeTypes(result) "getSupportedSignMimeTypes" -> handleGetSupportedSignMimeTypes(result) @@ -309,6 +313,52 @@ class C2paPlugin : FlutterPlugin, MethodCallHandler { } } + private fun handleGetRemoteUrl(call: MethodCall, result: Result) { + val path = call.argument("path") + if (path == null) { + result.error("INVALID_ARGUMENT", "Path is required", null) + return + } + val mimeType = call.argument("mimeType") ?: getMimeTypeFromPath(path) + try { + val stream = FileStream(File(path), FileStream.Mode.READ, createIfNeeded = false) + val reader = Reader.fromStream(mimeType, stream) + try { + result.success(reader.remoteUrl()) + } finally { + reader.close() + stream.close() + } + } catch (e: C2PAError) { + result.error("C2PA_ERROR", e.message, null) + } catch (e: Exception) { + result.error("ERROR", e.message, null) + } + } + + private fun handleIsManifestEmbedded(call: MethodCall, result: Result) { + val path = call.argument("path") + if (path == null) { + result.error("INVALID_ARGUMENT", "Path is required", null) + return + } + val mimeType = call.argument("mimeType") ?: getMimeTypeFromPath(path) + try { + val stream = FileStream(File(path), FileStream.Mode.READ, createIfNeeded = false) + val reader = Reader.fromStream(mimeType, stream) + try { + result.success(reader.isEmbedded()) + } finally { + reader.close() + stream.close() + } + } catch (e: C2PAError) { + result.error("C2PA_ERROR", e.message, null) + } catch (e: Exception) { + result.error("ERROR", e.message, null) + } + } + private fun handleGetSupportedReadMimeTypes(result: Result) { // Return common supported MIME types - the C2PA library supports these formats val mimeTypes = listOf( @@ -747,20 +797,20 @@ class C2paPlugin : FlutterPlugin, MethodCallHandler { val digitalSourceType = json.optString("digitalSourceType", null) // Parse parameters if present - val parameters = mutableMapOf() + val parameters = mutableMapOf() if (json.has("parameters")) { val paramsJson = json.getJSONObject("parameters") val keys = paramsJson.keys() while (keys.hasNext()) { val key = keys.next() - parameters[key] = paramsJson.optString(key, "") + parameters[key] = JsonPrimitive(paramsJson.optString(key, "")) } } val action = Action( actionName, digitalSourceType, - softwareAgent, + softwareAgent?.let { JsonPrimitive(it) }, if (parameters.isEmpty()) null else parameters ) diff --git a/example/integration_test/plugin_integration_test.dart b/example/integration_test/plugin_integration_test.dart index edfb726..641a163 100644 --- a/example/integration_test/plugin_integration_test.dart +++ b/example/integration_test/plugin_integration_test.dart @@ -190,7 +190,9 @@ void main() { final json = manifest.toJsonString(); expect(json, contains('AI Art')); - expect(json, contains('c2pa.ai_generated')); + // AI-generated content is a created action with the + // trainedAlgorithmicMedia source type; there is no dedicated action. + expect(json, contains('c2pa.created')); expect(json, contains('trainedAlgorithmicMedia')); expect(json, contains('c2pa.training-mining')); }); @@ -207,10 +209,13 @@ void main() { final cropped = Action.cropped(); expect(cropped.action, 'c2pa.cropped'); - final aiGenerated = Action.aiGenerated( + // AI-generated content is tagged via DigitalSourceType on a created + // action (spec-compliant), not via a custom action string. + final aiGenerated = Action.created( sourceType: DigitalSourceType.trainedAlgorithmicMedia, ); - expect(aiGenerated.action, 'c2pa.ai_generated'); + expect(aiGenerated.action, 'c2pa.created'); + expect(aiGenerated.digitalSourceType, contains('trainedAlgorithmicMedia')); }); testWidgets('Ingredient factories create correct ingredients', (tester) async { diff --git a/example/ios/Flutter/AppFrameworkInfo.plist b/example/ios/Flutter/AppFrameworkInfo.plist index 1dc6cf7..391a902 100644 --- a/example/ios/Flutter/AppFrameworkInfo.plist +++ b/example/ios/Flutter/AppFrameworkInfo.plist @@ -20,7 +20,5 @@ ???? CFBundleVersion 1.0 - MinimumOSVersion - 13.0 diff --git a/example/pubspec.lock b/example/pubspec.lock index 3af1bd8..201efa1 100644 --- a/example/pubspec.lock +++ b/example/pubspec.lock @@ -31,7 +31,7 @@ packages: path: ".." relative: true source: path - version: "0.0.2" + version: "0.0.3" camera: dependency: "direct main" description: @@ -76,10 +76,10 @@ packages: dependency: transitive description: name: characters - sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b url: "https://pub.dev" source: hosted - version: "1.4.0" + version: "1.4.1" clock: dependency: transitive description: @@ -354,18 +354,18 @@ packages: dependency: transitive description: name: matcher - sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 + sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861 url: "https://pub.dev" source: hosted - version: "0.12.17" + version: "0.12.19" material_color_utilities: dependency: transitive description: name: material_color_utilities - sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" url: "https://pub.dev" source: hosted - version: "0.11.1" + version: "0.13.0" meta: dependency: transitive description: @@ -655,10 +655,10 @@ packages: dependency: transitive description: name: test_api - sha256: ab2726c1a94d3176a45960b6234466ec367179b87dd74f1611adb1f3b5fb9d55 + sha256: "8161c84903fd860b26bfdefb7963b3f0b68fee7adea0f59ef805ecca346f0c7a" url: "https://pub.dev" source: hosted - version: "0.7.7" + version: "0.7.10" typed_data: dependency: transitive description: diff --git a/ios/c2pa_flutter/Package.swift b/ios/c2pa_flutter/Package.swift index 4a6e324..45f8c0e 100644 --- a/ios/c2pa_flutter/Package.swift +++ b/ios/c2pa_flutter/Package.swift @@ -23,7 +23,7 @@ let package = Package( .library(name: "c2pa-flutter", targets: ["c2pa_flutter"]) ], dependencies: [ - .package(url: "https://github.com/redaranj/c2pa-ios.git", exact: "0.0.9-beta.7") + .package(url: "https://github.com/contentauth/c2pa-ios.git", exact: "0.0.9") ], targets: [ .target( diff --git a/ios/c2pa_flutter/Sources/c2pa_flutter/C2paPlugin.swift b/ios/c2pa_flutter/Sources/c2pa_flutter/C2paPlugin.swift index 05d91e0..1271643 100644 --- a/ios/c2pa_flutter/Sources/c2pa_flutter/C2paPlugin.swift +++ b/ios/c2pa_flutter/Sources/c2pa_flutter/C2paPlugin.swift @@ -18,8 +18,15 @@ import C2PA /// Since the c2pa-ios library uses a global settings load rather than an /// object, we store the accumulated settings strings so they can be /// re-applied (merged) when creating signers or contexts. +/// +/// `currentJSON` tracks the most recently applied full JSON representation +/// so that `settingsSetValue` can parse → modify → re-serialize → re-apply +/// without depending on C2PASettings's private state. `setValue` normalizes +/// to a full JSON load in the segments list, so chronological replay +/// reproduces the final state. private struct SettingsEntry { var segments: [(settings: String, format: String)] + var currentJSON: String } public class C2paPlugin: NSObject, FlutterPlugin { @@ -67,6 +74,10 @@ public class C2paPlugin: NSObject, FlutterPlugin { handleExtractResource(call: call, result: result) case "readIngredientFile": handleReadIngredientFile(call: call, result: result) + case "getRemoteUrl": + handleGetRemoteUrl(call: call, result: result) + case "isManifestEmbedded": + handleIsManifestEmbedded(call: call, result: result) case "signBytes": handleSignBytes(call: call, result: result) case "signFile": @@ -138,6 +149,27 @@ public class C2paPlugin: NSObject, FlutterPlugin { // Certificate Manager case "createSelfSignedCertificateChain": handleCreateSelfSignedCertificateChain(call: call, result: result) + + case "createHashedPlaceholder", + "signHashedEmbeddable", + "formatEmbeddable": + result(FlutterError( + code: "NOT_IMPLEMENTED_IOS", + message: "\(call.method) is not yet implemented on iOS. " + + "Blocked on c2pa-ios exposing Builder.dataHashedPlaceholder / " + + "signDataHashedEmbeddable / format_embeddable_manifest as public Swift API.", + details: nil + )) + case "importKey", + "createCSR", + "enrollHardwareKey": + result(FlutterError( + code: "NOT_IMPLEMENTED_IOS", + message: "\(call.method) is not yet implemented on iOS (scheduled). " + + "Flutter API is defined and Android works; iOS plugin handler pending.", + details: nil + )) + default: result(FlutterMethodNotImplemented) } @@ -310,6 +342,44 @@ public class C2paPlugin: NSObject, FlutterPlugin { } } + private func handleGetRemoteUrl(call: FlutterMethodCall, result: @escaping FlutterResult) { + guard let args = call.arguments as? [String: Any], + let path = args["path"] as? String else { + result(FlutterError(code: "INVALID_ARGUMENT", message: "Path is required", details: nil)) + return + } + + let mimeType = (args["mimeType"] as? String) + ?? mimeTypeForExtension((path as NSString).pathExtension.lowercased()) + + do { + let stream = try Stream(readFrom: URL(fileURLWithPath: path)) + let reader = try Reader(format: mimeType, stream: stream) + result(reader.remote()?.absoluteString) + } catch { + result(FlutterError(code: "C2PA_ERROR", message: error.localizedDescription, details: nil)) + } + } + + private func handleIsManifestEmbedded(call: FlutterMethodCall, result: @escaping FlutterResult) { + guard let args = call.arguments as? [String: Any], + let path = args["path"] as? String else { + result(FlutterError(code: "INVALID_ARGUMENT", message: "Path is required", details: nil)) + return + } + + let mimeType = (args["mimeType"] as? String) + ?? mimeTypeForExtension((path as NSString).pathExtension.lowercased()) + + do { + let stream = try Stream(readFrom: URL(fileURLWithPath: path)) + let reader = try Reader(format: mimeType, stream: stream) + result(reader.isEmbedded()) + } catch { + result(FlutterError(code: "C2PA_ERROR", message: error.localizedDescription, details: nil)) + } + } + // MARK: - Signer Creation private func createSigner(_ signerMap: [String: Any], result: @escaping FlutterResult, completion: @escaping (Signer) -> Void) { @@ -362,14 +432,14 @@ public class C2paPlugin: NSObject, FlutterPlugin { throw C2PAError.api("Invalid PEM signer configuration") } - let tsaUrl = signerMap["tsaUrl"] as? String + let tsaUrl = (signerMap["tsaUrl"] as? String).flatMap(URL.init(string:)) let algorithm = mapAlgorithm(algorithmStr) return try Signer( certsPEM: certificatePem, privateKeyPEM: privateKeyPem, algorithm: algorithm, - tsaURL: tsaUrl + tsa: tsaUrl ) } @@ -380,13 +450,13 @@ public class C2paPlugin: NSObject, FlutterPlugin { throw C2PAError.api("Invalid keychain signer configuration") } - let tsaUrl = signerMap["tsaUrl"] as? String + let tsaUrl = (signerMap["tsaUrl"] as? String).flatMap(URL.init(string:)) let algorithm = mapAlgorithm(algorithmStr) return try Signer( algorithm: algorithm, certificateChainPEM: certificateChainPem, - tsaURL: tsaUrl, + tsa: tsaUrl, keychainKeyTag: keyAlias ) } @@ -397,7 +467,7 @@ public class C2paPlugin: NSObject, FlutterPlugin { throw C2PAError.api("Invalid Secure Enclave signer configuration") } - let tsaUrl = signerMap["tsaUrl"] as? String + let tsaUrl = (signerMap["tsaUrl"] as? String).flatMap(URL.init(string:)) let requireUserAuth = signerMap["requireUserAuthentication"] as? Bool ?? false var accessControl: SecAccessControlCreateFlags = [.privateKeyUsage] @@ -413,7 +483,7 @@ public class C2paPlugin: NSObject, FlutterPlugin { return try Signer( algorithm: .es256, certificateChainPEM: certificateChainPem, - tsaURL: tsaUrl, + tsa: tsaUrl, secureEnclaveConfig: config ) } @@ -425,13 +495,13 @@ public class C2paPlugin: NSObject, FlutterPlugin { throw C2PAError.api("Invalid callback signer configuration") } - let tsaUrl = signerMap["tsaUrl"] as? String + let tsaUrl = (signerMap["tsaUrl"] as? String).flatMap(URL.init(string:)) let algorithm = mapAlgorithm(algorithmStr) return try Signer( algorithm: algorithm, certificateChainPEM: certificateChainPem, - tsaURL: tsaUrl + tsa: tsaUrl ) { [weak self] dataToSign in guard let self = self, let channel = self.methodChannel else { throw C2PAError.api("Method channel not available") @@ -470,7 +540,8 @@ public class C2paPlugin: NSObject, FlutterPlugin { } private func createRemoteSigner(_ signerMap: [String: Any], completion: @escaping (Result) -> Void) { - guard let configurationUrl = signerMap["configurationUrl"] as? String else { + guard let configurationUrl = signerMap["configurationUrl"] as? String, + let configurationEndpoint = URL(string: configurationUrl) else { completion(.failure(C2PAError.api("Invalid remote signer configuration"))) return } @@ -479,7 +550,7 @@ public class C2paPlugin: NSObject, FlutterPlugin { let customHeaders = signerMap["customHeaders"] as? [String: String] ?? [:] let webServiceSigner = WebServiceSigner( - configurationURL: configurationUrl, + configurationEndpoint: configurationEndpoint, bearerToken: bearerToken, headers: customHeaders ) @@ -669,7 +740,8 @@ public class C2paPlugin: NSObject, FlutterPlugin { private func handleBuilderSetRemoteUrl(call: FlutterMethodCall, result: @escaping FlutterResult) { guard let args = call.arguments as? [String: Any], let handle = args["handle"] as? Int, - let url = args["url"] as? String else { + let url = args["url"] as? String, + let remoteURL = URL(string: url) else { result(FlutterError(code: "INVALID_ARGUMENT", message: "handle and url are required", details: nil)) return } @@ -680,7 +752,7 @@ public class C2paPlugin: NSObject, FlutterPlugin { } do { - try builder.setRemoteURL(url) + try builder.setRemote(url: remoteURL) result(nil) } catch { result(FlutterError(code: "C2PA_ERROR", message: error.localizedDescription, details: nil)) @@ -779,11 +851,13 @@ public class C2paPlugin: NSObject, FlutterPlugin { let actionDict = try JSONSerialization.jsonObject(with: actionData) as? [String: Any], let actionName = actionDict["action"] as? String { let digitalSourceTypeStr = actionDict["digitalSourceType"] as? String + let parameters = (actionDict["parameters"] as? [String: Any])? + .mapValues { AnyCodable($0) } let action = Action( action: actionName, digitalSourceType: digitalSourceTypeStr, softwareAgent: actionDict["softwareAgent"] as? String, - parameters: actionDict["parameters"] as? [String: String] + parameters: parameters ) try builder.addAction(action) } @@ -976,8 +1050,13 @@ public class C2paPlugin: NSObject, FlutterPlugin { return } + guard let settingsFormat = Signer.SettingsFormat(rawValue: format.lowercased()) else { + result(FlutterError(code: "INVALID_ARGUMENT", message: "format must be 'json' or 'toml'", details: nil)) + return + } + do { - try Signer.loadSettings(settings, format: format) + try Signer.loadSettings(settings, format: settingsFormat) result(nil) } catch { result(FlutterError(code: "C2PA_ERROR", message: error.localizedDescription, details: nil)) @@ -987,7 +1066,7 @@ public class C2paPlugin: NSObject, FlutterPlugin { // MARK: - Settings Handle API private func handleCreateSettings(result: @escaping FlutterResult) { - let handle = storeSettings(SettingsEntry(segments: [])) + let handle = storeSettings(SettingsEntry(segments: [], currentJSON: "{\"version\":1}")) result(handle) } @@ -1000,7 +1079,7 @@ public class C2paPlugin: NSObject, FlutterPlugin { return } - guard format.lowercased() == "json" || format.lowercased() == "toml" else { + guard let settingsFormat = Signer.SettingsFormat(rawValue: format.lowercased()) else { result(FlutterError(code: "INVALID_ARGUMENT", message: "format must be 'json' or 'toml'", details: nil)) return } @@ -1011,12 +1090,15 @@ public class C2paPlugin: NSObject, FlutterPlugin { result(FlutterError(code: "INVALID_HANDLE", message: "Settings not found", details: nil)) return } - settingsMap[handle]!.segments.append((settings: settings, format: format.lowercased())) + settingsMap[handle]!.segments.append((settings: settings, format: settingsFormat.rawValue)) + if settingsFormat == .json { + settingsMap[handle]!.currentJSON = settings + } settingsLock.unlock() // Also apply the settings globally so they take effect immediately do { - try Signer.loadSettings(settings, format: format.lowercased()) + try Signer.loadSettings(settings, format: settingsFormat) result(nil) } catch { result(FlutterError(code: "C2PA_ERROR", message: error.localizedDescription, details: nil)) @@ -1024,15 +1106,66 @@ public class C2paPlugin: NSObject, FlutterPlugin { } private func handleSettingsSetValue(call: FlutterMethodCall, result: @escaping FlutterResult) { - // The c2pa-ios library does not expose a method to set individual - // settings values. Settings are loaded as complete JSON or TOML - // documents via Signer.loadSettings(). Individual key/value - // setting is not supported on iOS. - result(FlutterError( - code: "NOT_SUPPORTED", - message: "settingsSetValue is not supported on iOS. Use settingsUpdateFromString to load a complete settings document.", - details: nil - )) + guard let args = call.arguments as? [String: Any], + let handle = args["handle"] as? Int, + let path = args["path"] as? String else { + result(FlutterError(code: "INVALID_ARGUMENT", message: "handle and path are required", details: nil)) + return + } + let value: Any = args["value"] ?? NSNull() + + settingsLock.lock() + guard var entry = settingsMap[handle] else { + settingsLock.unlock() + result(FlutterError(code: "INVALID_HANDLE", message: "Settings not found", details: nil)) + return + } + let currentJSON = entry.currentJSON + settingsLock.unlock() + + do { + guard let data = currentJSON.data(using: .utf8), + var dict = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { + throw C2PAError.api("Current settings are not a valid JSON object") + } + + let components = path.split(separator: ".").map(String.init) + guard !components.isEmpty else { + throw C2PAError.api("Path must not be empty") + } + Self.setNestedValue(&dict, components: components, value: value) + + let updatedData = try JSONSerialization.data(withJSONObject: dict) + guard let updatedString = String(data: updatedData, encoding: .utf8) else { + throw C2PAError.utf8 + } + + try Signer.loadSettings(updatedString, format: .json) + + settingsLock.lock() + entry = settingsMap[handle] ?? entry + entry.currentJSON = updatedString + entry.segments.append((settings: updatedString, format: "json")) + settingsMap[handle] = entry + settingsLock.unlock() + + result(nil) + } catch let error as C2PAError { + result(FlutterError(code: "C2PA_ERROR", message: error.errorDescription, details: nil)) + } catch { + result(FlutterError(code: "C2PA_ERROR", message: error.localizedDescription, details: nil)) + } + } + + private static func setNestedValue(_ dict: inout [String: Any], components: [String], value: Any) { + guard let key = components.first else { return } + if components.count == 1 { + dict[key] = value + } else { + var nested = dict[key] as? [String: Any] ?? [:] + setNestedValue(&nested, components: Array(components.dropFirst()), value: value) + dict[key] = nested + } } private func handleSettingsDispose(call: FlutterMethodCall, result: @escaping FlutterResult) { @@ -1050,7 +1183,7 @@ public class C2paPlugin: NSObject, FlutterPlugin { private func handleCreateContext(result: @escaping FlutterResult) { // Create an empty settings entry to back this context - let settingsHandle = storeSettings(SettingsEntry(segments: [])) + let settingsHandle = storeSettings(SettingsEntry(segments: [], currentJSON: "{\"version\":1}")) let contextHandle = storeContext(settingsHandle: settingsHandle) result(contextHandle) } @@ -1460,7 +1593,8 @@ public class C2paPlugin: NSObject, FlutterPlugin { } for segment in entry.segments { - try Signer.loadSettings(segment.settings, format: segment.format) + guard let format = Signer.SettingsFormat(rawValue: segment.format) else { continue } + try Signer.loadSettings(segment.settings, format: format) } } diff --git a/lib/c2pa.dart b/lib/c2pa.dart index aeeaef8..f74f541 100644 --- a/lib/c2pa.dart +++ b/lib/c2pa.dart @@ -107,10 +107,12 @@ import 'package:meta/meta.dart'; import 'c2pa_platform_interface.dart'; import 'src/manifest_types.dart'; +import 'src/settings_definition.dart'; // Export manifest types export 'src/manifest_types.dart'; export 'src/manifest_validator.dart'; +export 'src/settings_definition.dart'; export 'src/settings_validator.dart'; // ============================================================================= @@ -1098,6 +1100,18 @@ abstract class ManifestBuilder { IngredientConfig? config, }); + /// Add an ingredient from a file path. + /// + /// Prefer this over [addIngredient] for large files — the native plugin reads + /// the file directly and avoids round-tripping the bytes through the Dart VM. + /// + /// If [mimeType] is null, the native side infers it from the file extension. + Future addIngredientFromFile({ + required String path, + String? mimeType, + IngredientConfig? config, + }); + /// Add an action to the manifest void addAction(ActionConfig action); @@ -1152,6 +1166,18 @@ class C2paSettings { return C2paSettings._(handle); } + /// Create a new settings instance initialized from a typed + /// [C2paSettingsDefinition]. + /// + /// The definition is serialized to JSON and applied immediately. + static Future fromDefinition( + C2paSettingsDefinition definition, + ) async { + final settings = await create(); + await settings.updateFromDefinition(definition); + return settings; + } + /// Update settings from a JSON or TOML string. /// /// The [format] should be 'json' or 'toml'. @@ -1164,9 +1190,24 @@ class C2paSettings { ); } + /// Update settings from a typed [C2paSettingsDefinition]. + /// + /// The definition is serialized to JSON and applied via [updateFromString]. + /// This is the preferred way to build settings programmatically — + /// it mirrors `C2PASettings.init(definition:)` on iOS and + /// `C2PASettings.fromDefinition(...)` on Android. + Future updateFromDefinition(C2paSettingsDefinition definition) { + return updateFromString(definition.toJsonString(), 'json'); + } + /// Set an individual setting value using dot notation. /// /// Example: `await settings.setValue('verify.verify_trust', 'false');` + /// + /// **Platform note.** Both platforms accept the value as a JSON-compatible + /// primitive, but the Android plugin currently only widens to String at the + /// channel boundary. Pass values as strings for cross-platform safety + /// (e.g. `'true'`, `'42'`, `'es256'`). Future setValue(String path, String value) { _checkDisposed(); return C2paPlatform.instance.settingsSetValue(_handle, path, value); @@ -1428,6 +1469,22 @@ class C2pa { return C2paPlatform.instance.readIngredientFile(path, dataDir); } + /// Return the remote manifest URL embedded in the file at [path], if any. + /// + /// Returns null when the asset has no manifest or when the manifest is + /// embedded (no remote reference). + Future getRemoteUrl(String path, {String? mimeType}) { + return C2paPlatform.instance.getRemoteUrl(path, mimeType: mimeType); + } + + /// Return whether the manifest at [path] is embedded in the file itself. + /// + /// Returns false when no manifest is present or the manifest is stored + /// remotely and only referenced from the asset. + Future isManifestEmbedded(String path, {String? mimeType}) { + return C2paPlatform.instance.isManifestEmbedded(path, mimeType: mimeType); + } + /// Get supported MIME types for reading Future> getSupportedReadMimeTypes() { return C2paPlatform.instance.getSupportedReadMimeTypes(); @@ -1492,10 +1549,14 @@ class C2pa { // Advanced Signing API // =========================================================================== - /// Create a hashed placeholder for later signing + /// Create a hashed placeholder for later signing. /// /// This is used for advanced signing workflows where the asset /// needs to be prepared before the actual signing occurs. + /// + /// **Platform note.** Android is implemented. iOS currently throws + /// `NOT_IMPLEMENTED_IOS` — blocked on c2pa-ios exposing + /// `Builder.dataHashedPlaceholder` as public Swift API. Future createHashedPlaceholder({ required ManifestBuilder builder, required int reservedSize, @@ -1508,9 +1569,13 @@ class C2pa { ); } - /// Sign a data-hashed embeddable manifest + /// Sign a data-hashed embeddable manifest. + /// + /// This is used after [createHashedPlaceholder] for advanced signing workflows. /// - /// This is used after createHashedPlaceholder for advanced signing workflows. + /// **Platform note.** Android is implemented. iOS currently throws + /// `NOT_IMPLEMENTED_IOS` — blocked on c2pa-ios exposing + /// `Builder.signDataHashedEmbeddable` as public Swift API. Future signHashedEmbeddable({ required ManifestBuilder builder, required C2paSigner signer, @@ -1527,14 +1592,16 @@ class C2pa { ); } - /// Convert raw manifest bytes to an embeddable format + /// Convert raw manifest bytes to an embeddable format. /// /// A raw manifest (application/c2pa format) cannot be embedded directly. /// This converts it to an embeddable format for the specified MIME type. /// - /// **Android note**: This method returns the input unchanged on Android as - /// the native library does not support this operation. The manifest bytes - /// from [signHashedEmbeddable] are already in the correct format on Android. + /// **Platform notes.** + /// - Android: returns the input unchanged; manifest bytes from + /// [signHashedEmbeddable] are already in the correct format. + /// - iOS: currently throws `NOT_IMPLEMENTED_IOS` — blocked on c2pa-ios + /// exposing `c2pa_format_embeddable_manifest` via a public Swift wrapper. Future formatEmbeddable({ required String mimeType, required Uint8List manifestBytes, @@ -1612,8 +1679,10 @@ class C2pa { /// This allows using externally generated keys (e.g., test certificates) /// with the Keystore signer. The private key must be in PKCS#8 PEM format. /// - /// Note: On Android, this imports into AndroidKeyStore. The key will not - /// have hardware protection even if StrongBox is available. + /// **Platform notes.** + /// - Android: imports into AndroidKeyStore. The key will not have hardware + /// protection even if StrongBox is available. + /// - iOS: currently throws `NOT_IMPLEMENTED_IOS` (scheduled). Future importKey({ required String keyAlias, required String privateKeyPem, @@ -1630,6 +1699,10 @@ class C2pa { /// /// The key must already exist in the platform keystore (created via [createKey]). /// Returns a PEM-encoded CSR that can be submitted to a signing server. + /// + /// **Platform note.** Android is implemented. iOS currently throws + /// `NOT_IMPLEMENTED_IOS` (scheduled — `CertificateManager.createCSR(keyTag:config:)` + /// on iOS is public and usable once the plugin handler is wired up). Future createCSR({ required String keyAlias, required String commonName, @@ -1658,6 +1731,11 @@ class C2pa { /// Returns a map containing: /// - `certificateChain`: The PEM-encoded certificate chain from the server /// - `keyAlias`: The key alias used + /// + /// **Platform note.** Android is implemented via + /// `CertificateManager.createSignerWithCSR`. iOS currently throws + /// `NOT_IMPLEMENTED_IOS` (scheduled — the plugin needs to compose + /// `createKey` + `CertificateManager.createCSR` + `URLSession` POST). Future> enrollHardwareKey({ required String keyAlias, required String signingServerUrl, diff --git a/lib/c2pa_method_channel.dart b/lib/c2pa_method_channel.dart index 22faa66..fe5ff99 100644 --- a/lib/c2pa_method_channel.dart +++ b/lib/c2pa_method_channel.dart @@ -89,6 +89,23 @@ class MethodChannelC2pa extends C2paPlatform { return version; } + @override + Future getRemoteUrl(String path, {String? mimeType}) async { + return methodChannel.invokeMethod('getRemoteUrl', { + 'path': path, + 'mimeType': mimeType, + }); + } + + @override + Future isManifestEmbedded(String path, {String? mimeType}) async { + final result = await methodChannel.invokeMethod( + 'isManifestEmbedded', + {'path': path, 'mimeType': mimeType}, + ); + return result ?? false; + } + // ============================================================================= // Reader API - Basic // ============================================================================= @@ -343,6 +360,21 @@ class MethodChannelC2pa extends C2paPlatform { }); } + @override + Future builderAddIngredientFromFile( + int handle, + String path, + String? mimeType, + String? ingredientJson, + ) async { + await methodChannel.invokeMethod('builderAddIngredientFromFile', { + 'handle': handle, + 'filePath': path, + 'mimeType': mimeType, + 'ingredientJson': ingredientJson, + }); + } + @override Future builderAddAction(int handle, String actionJson) async { await methodChannel.invokeMethod('builderAddAction', { @@ -918,6 +950,21 @@ class MethodChannelManifestBuilder implements ManifestBuilder { ); } + @override + Future addIngredientFromFile({ + required String path, + String? mimeType, + IngredientConfig? config, + }) async { + _checkDisposed(); + await _platform.builderAddIngredientFromFile( + _handle, + path, + mimeType, + config?.toJson(), + ); + } + @override void addAction(ActionConfig action) { _checkDisposed(); diff --git a/lib/c2pa_platform_interface.dart b/lib/c2pa_platform_interface.dart index de3d645..7da9a01 100644 --- a/lib/c2pa_platform_interface.dart +++ b/lib/c2pa_platform_interface.dart @@ -101,6 +101,18 @@ abstract class C2paPlatform extends PlatformInterface { throw UnimplementedError('readIngredientFile() has not been implemented.'); } + /// Returns the remote manifest URL for a file at [path], if any. + /// Returns null when the file has no manifest or no remote URL. + Future getRemoteUrl(String path, {String? mimeType}) { + throw UnimplementedError('getRemoteUrl() has not been implemented.'); + } + + /// Returns whether the manifest at [path] is embedded in the file (true) or + /// only referenced by a remote URL (false). Returns false when no manifest is present. + Future isManifestEmbedded(String path, {String? mimeType}) { + throw UnimplementedError('isManifestEmbedded() has not been implemented.'); + } + /// Returns the list of MIME types supported for reading. Future> getSupportedReadMimeTypes() { throw UnimplementedError( @@ -191,6 +203,19 @@ abstract class C2paPlatform extends PlatformInterface { ); } + /// Adds an ingredient from a file at [path] to the builder at [handle]. + /// If [mimeType] is null, the native side infers it from the file extension. + Future builderAddIngredientFromFile( + int handle, + String path, + String? mimeType, + String? ingredientJson, + ) { + throw UnimplementedError( + 'builderAddIngredientFromFile() has not been implemented.', + ); + } + /// Adds an action from [actionJson] to the builder at [handle]. Future builderAddAction(int handle, String actionJson) { throw UnimplementedError('builderAddAction() has not been implemented.'); diff --git a/lib/src/manifest_types.dart b/lib/src/manifest_types.dart index 148d6bb..faf6808 100644 --- a/lib/src/manifest_types.dart +++ b/lib/src/manifest_types.dart @@ -25,37 +25,161 @@ import 'package:meta/meta.dart'; // Enums // ============================================================================= -/// Standard C2PA action identifiers +/// Standard C2PA action identifiers. /// /// These represent the predefined actions in the C2PA specification. /// Use [value] to get the string representation for JSON serialization. +/// +/// This list is kept in sync with the native c2pa-ios and c2pa-android SDKs +/// (both at v0.0.9 as of this writing) — 33 `c2pa.*` actions plus 11 `font.*` +/// actions from the Font Content Specification. enum PredefinedAction { - created('c2pa.created'), - edited('c2pa.edited'), + /// (visible) Textual content was inserted into the asset, such as on a text + /// layer or as a caption. + addedText('c2pa.addedText'), + + /// Changes to tone, saturation, etc. + adjustedColor('c2pa.adjustedColor'), + + /// Reduced or increased playback speed of a video or audio track. + changedSpeed('c2pa.changedSpeed'), + + /// Deprecated — use [adjustedColor]. + @Deprecated('Use PredefinedAction.adjustedColor') + colorAdjustments('c2pa.color_adjustments'), + + /// The format of the asset was changed. converted('c2pa.converted'), - compressed('c2pa.compressed'), + + /// The asset was first created. + created('c2pa.created'), + + /// Areas of the asset's digital content were cropped out. cropped('c2pa.cropped'), + + /// Areas of the asset's digital content were deleted. + deleted('c2pa.deleted'), + + /// Changes using drawing tools including brushes or eraser. drawing('c2pa.drawing'), + + /// Changes were made to audio, usually one or more tracks of a composite + /// asset. + dubbed('c2pa.dubbed'), + + /// Generalized actions that would be considered editorial transformations + /// of the content. + edited('c2pa.edited'), + + /// Modifications to asset metadata or a metadata assertion but not the + /// asset's digital content. + editedMetadata('c2pa.edited.metadata'), + + /// Applied enhancements such as noise reduction, multi-band compression, or + /// sharpening that represent non-editorial transformations of the content. + enhanced('c2pa.enhanced'), + + /// Changes to appearance with applied filters, styles, etc. filtered('c2pa.filtered'), + + /// Final production step where assets are prepared for distribution. + mastered('c2pa.mastered'), + + /// Multiple audio ingredients (stems, vocals, drums, etc.) are combined + /// and transformed. + mixed('c2pa.mixed'), + + /// An existing asset was opened and is being set as the parentOf ingredient. opened('c2pa.opened'), + + /// Changes to the direction and position of content. orientation('c2pa.orientation'), + + /// Added/Placed one or more componentOf ingredient(s) into the asset. placed('c2pa.placed'), + + /// Asset is released to a wider audience. published('c2pa.published'), + + /// One or more assertions were redacted. redacted('c2pa.redacted'), + + /// Components from one or more ingredients were combined in a + /// transformative way. + remixed('c2pa.remixed'), + + /// A componentOf ingredient was removed. removed('c2pa.removed'), + + /// A conversion of one packaging or container format to another. + /// Content is repackaged without transcoding. repackaged('c2pa.repackaged'), + + /// Changes to either content dimensions, its file size or both. resized('c2pa.resized'), + + /// Dimensions were changed while maintaining aspect ratio. + resizedProportional('c2pa.resized.proportional'), + + /// A conversion of one encoding to another, including resolution scaling, + /// bitrate adjustment and encoding format change. transcoded('c2pa.transcoded'), + + /// Changes to the language of the content. translated('c2pa.translated'), + + /// Removal of a temporal range of the content. + trimmed('c2pa.trimmed'), + + /// Something happened, but the claim_generator cannot specify what. + unknown('c2pa.unknown'), + + /// An invisible watermark was inserted into the digital content for the + /// purpose of creating a soft binding. watermarked('c2pa.watermarked'), - aiGenerated('c2pa.ai_generated'), - aiTrained('c2pa.ai_trained'), - derivedFrom('c2pa.derived_from'), - color('c2pa.color'), - combined('c2pa.combined'), - compositeUsed('c2pa.composite_used'), - contentSummary('c2pa.content_summary'), - adjustments('c2pa.adjustments'); + + /// An invisible watermark was inserted that is cryptographically bound to + /// this manifest (soft binding). + watermarkedBound('c2pa.watermarked.bound'), + + /// An invisible watermark was inserted that is NOT cryptographically bound + /// to this manifest. + watermarkedUnbound('c2pa.watermarked.unbound'), + + // Font Content Specification actions. + + /// Characters or character sets were added to the font. + fontCharactersAdded('font.charactersAdded'), + + /// Characters or character sets were deleted from the font. + fontCharactersDeleted('font.charactersDeleted'), + + /// Characters were both added and deleted from the font. + fontCharactersModified('font.charactersModified'), + + /// A font was instantiated from a variable font. + fontCreatedFromVariableFont('font.createdFromVariableFont'), + + /// The font was edited (catch-all). + fontEdited('font.edited'), + + /// Hinting was applied to the font. + fontHinted('font.hinted'), + + /// A combination of antecedent fonts. + fontMerged('font.merged'), + + /// An OpenType feature was added. + fontOpenTypeFeatureAdded('font.openTypeFeatureAdded'), + + /// An OpenType feature was modified. + fontOpenTypeFeatureModified('font.openTypeFeatureModified'), + + /// An OpenType feature was removed. + fontOpenTypeFeatureRemoved('font.openTypeFeatureRemoved'), + + /// The font was stripped to a sub-group of characters. + fontSubset('font.subset'); const PredefinedAction(this.value); final String value; @@ -1034,16 +1158,22 @@ class Action { this.reason, }); - /// Create a "created" action + /// Create a "created" action. + /// + /// For AI-generated content, set [sourceType] to + /// [DigitalSourceType.trainedAlgorithmicMedia] (or another AI-related source + /// type) — this is the spec-compliant way to tag AI-generated assets. factory Action.created({ DigitalSourceType? sourceType, String? softwareAgent, + Map? parameters, String? when, }) { return Action( action: PredefinedAction.created.value, digitalSourceType: sourceType?.url, softwareAgent: softwareAgent, + parameters: parameters, when: when, ); } @@ -1134,22 +1264,6 @@ class Action { ); } - /// Create an "AI generated" action - factory Action.aiGenerated({ - DigitalSourceType? sourceType, - String? softwareAgent, - Map? parameters, - String? when, - }) { - return Action( - action: PredefinedAction.aiGenerated.value, - digitalSourceType: sourceType?.url, - softwareAgent: softwareAgent, - parameters: parameters, - when: when, - ); - } - /// Create a "converted" action factory Action.converted({ String? softwareAgent, @@ -1908,7 +2022,7 @@ class ManifestDefinition { assertions: [ ActionsAssertion( actions: [ - Action.aiGenerated( + Action.created( sourceType: sourceType, softwareAgent: claimGenerator.claimGeneratorString, parameters: parameters, diff --git a/lib/src/settings_definition.dart b/lib/src/settings_definition.dart new file mode 100644 index 0000000..dce560a --- /dev/null +++ b/lib/src/settings_definition.dart @@ -0,0 +1,781 @@ +/* +This file is licensed to you under the Apache License, Version 2.0 +(http://www.apache.org/licenses/LICENSE-2.0) or the MIT license +(http://opensource.org/licenses/MIT), at your option. + +Unless required by applicable law or agreed to in writing, this software is +distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF +ANY KIND, either express or implied. See the LICENSE-MIT and LICENSE-APACHE +files for the specific language governing permissions and limitations under +each license. +*/ + +/// Type-safe C2PA settings definition. +/// +/// Mirrors the `C2PASettingsDefinition` type exposed by c2pa-ios and +/// c2pa-android v0.0.9. Serializes to the same JSON shape both native SDKs +/// accept (snake_case keys). Use with [C2paSettings.updateFromDefinition] +/// to apply typed settings to a settings handle. +library; + +import 'dart:convert'; + +import 'package:meta/meta.dart'; + +// ============================================================================= +// Top-level settings container +// ============================================================================= + +/// A type-safe representation of the C2PA settings JSON schema. +/// +/// All fields are optional. Only set the values you need — unset fields are +/// omitted from the encoded JSON. +/// +/// ## Example +/// +/// ```dart +/// final definition = C2paSettingsDefinition( +/// version: 1, +/// signer: SignerSettings.local(LocalSignerSettings( +/// alg: 'es256', +/// signCert: certPem, +/// privateKey: keyPem, +/// tsaUrl: 'http://timestamp.digicert.com', +/// )), +/// ); +/// +/// final settings = await C2paSettings.create(); +/// await settings.updateFromDefinition(definition); +/// ``` +@immutable +class C2paSettingsDefinition { + /// The settings schema version. Currently `1`. + final int? version; + + /// Trust configuration for manifest verification. + final TrustSettings? trust; + + /// CAWG-specific trust configuration. + final TrustSettings? cawgTrust; + + /// Core library settings. + final CoreSettings? core; + + /// Verification behavior settings. + final VerifySettings? verify; + + /// Builder configuration. + final BuilderSettingsDefinition? builder; + + /// Signer configuration (local or remote). + final SignerSettings? signer; + + /// CAWG X.509 signer configuration. + final SignerSettings? cawgX509Signer; + + const C2paSettingsDefinition({ + this.version, + this.trust, + this.cawgTrust, + this.core, + this.verify, + this.builder, + this.signer, + this.cawgX509Signer, + }); + + Map toJson() { + final map = {}; + if (version != null) map['version'] = version; + if (trust != null) map['trust'] = trust!.toJson(); + if (cawgTrust != null) map['cawg_trust'] = cawgTrust!.toJson(); + if (core != null) map['core'] = core!.toJson(); + if (verify != null) map['verify'] = verify!.toJson(); + if (builder != null) map['builder'] = builder!.toJson(); + if (signer != null) map['signer'] = signer!.toJson(); + if (cawgX509Signer != null) { + map['cawg_x509_signer'] = cawgX509Signer!.toJson(); + } + return map; + } + + /// Encodes this definition to a compact JSON string. + String toJsonString() => jsonEncode(toJson()); +} + +// ============================================================================= +// Trust settings +// ============================================================================= + +/// Trust configuration for manifest verification. +@immutable +class TrustSettings { + /// Whether to verify against the trust list. + final bool? verifyTrustList; + + /// User-provided trust anchors in PEM format. + final String? userAnchors; + + /// Trust anchors in PEM format. + final String? trustAnchors; + + /// Trust configuration JSON. + final String? trustConfig; + + /// Allowed list of signing credentials. + final String? allowedList; + + const TrustSettings({ + this.verifyTrustList, + this.userAnchors, + this.trustAnchors, + this.trustConfig, + this.allowedList, + }); + + Map toJson() { + final map = {}; + if (verifyTrustList != null) map['verify_trust_list'] = verifyTrustList; + if (userAnchors != null) map['user_anchors'] = userAnchors; + if (trustAnchors != null) map['trust_anchors'] = trustAnchors; + if (trustConfig != null) map['trust_config'] = trustConfig; + if (allowedList != null) map['allowed_list'] = allowedList; + return map; + } +} + +// ============================================================================= +// Core settings +// ============================================================================= + +/// Core library configuration. +@immutable +class CoreSettings { + /// Chunk size for Merkle tree hashing, in kilobytes. + final int? merkleTreeChunkSizeInKb; + + /// Maximum number of Merkle tree proofs. + final int? merkleTreeMaxProofs; + + /// Memory threshold before switching to disk-backed storage, in megabytes. + final int? backingStoreMemoryThresholdInMb; + + /// Whether to decode identity assertions. + final bool? decodeIdentityAssertions; + + /// List of allowed network hosts for remote operations. + final List? allowedNetworkHosts; + + const CoreSettings({ + this.merkleTreeChunkSizeInKb, + this.merkleTreeMaxProofs, + this.backingStoreMemoryThresholdInMb, + this.decodeIdentityAssertions, + this.allowedNetworkHosts, + }); + + Map toJson() { + final map = {}; + if (merkleTreeChunkSizeInKb != null) { + map['merkle_tree_chunk_size_in_kb'] = merkleTreeChunkSizeInKb; + } + if (merkleTreeMaxProofs != null) { + map['merkle_tree_max_proofs'] = merkleTreeMaxProofs; + } + if (backingStoreMemoryThresholdInMb != null) { + map['backing_store_memory_threshold_in_mb'] = + backingStoreMemoryThresholdInMb; + } + if (decodeIdentityAssertions != null) { + map['decode_identity_assertions'] = decodeIdentityAssertions; + } + if (allowedNetworkHosts != null) { + map['allowed_network_hosts'] = allowedNetworkHosts; + } + return map; + } +} + +// ============================================================================= +// Verify settings +// ============================================================================= + +/// Verification behavior configuration. +@immutable +class VerifySettings { + /// Whether to verify manifests after reading. + final bool? verifyAfterReading; + + /// Whether to verify manifests after signing. + final bool? verifyAfterSign; + + /// Whether to verify trust chains. + final bool? verifyTrust; + + /// Whether to verify timestamp trust. + final bool? verifyTimestampTrust; + + /// Whether to fetch OCSP responses. + final bool? ocspFetch; + + /// Whether to fetch remote manifests. + final bool? remoteManifestFetch; + + /// Whether to skip ingredient conflict resolution. + final bool? skipIngredientConflictResolution; + + /// Whether to use strict v1 validation rules. + final bool? strictV1Validation; + + const VerifySettings({ + this.verifyAfterReading, + this.verifyAfterSign, + this.verifyTrust, + this.verifyTimestampTrust, + this.ocspFetch, + this.remoteManifestFetch, + this.skipIngredientConflictResolution, + this.strictV1Validation, + }); + + Map toJson() { + final map = {}; + if (verifyAfterReading != null) { + map['verify_after_reading'] = verifyAfterReading; + } + if (verifyAfterSign != null) map['verify_after_sign'] = verifyAfterSign; + if (verifyTrust != null) map['verify_trust'] = verifyTrust; + if (verifyTimestampTrust != null) { + map['verify_timestamp_trust'] = verifyTimestampTrust; + } + if (ocspFetch != null) map['ocsp_fetch'] = ocspFetch; + if (remoteManifestFetch != null) { + map['remote_manifest_fetch'] = remoteManifestFetch; + } + if (skipIngredientConflictResolution != null) { + map['skip_ingredient_conflict_resolution'] = + skipIngredientConflictResolution; + } + if (strictV1Validation != null) { + map['strict_v1_validation'] = strictV1Validation; + } + return map; + } +} + +// ============================================================================= +// Builder settings +// ============================================================================= + +/// Builder configuration within settings. +@immutable +class BuilderSettingsDefinition { + /// Vendor prefix for manifest labels. + final String? vendor; + + /// Claim generator information. + final ClaimGeneratorInfoSettings? claimGeneratorInfo; + + /// Thumbnail generation settings. + final ThumbnailSettings? thumbnail; + + /// Actions configuration. + final ActionsSettings? actions; + + /// Scope for fetching certificate status (OCSP). + final OcspFetchScope? certificateStatusFetch; + + /// Whether certificate status should override existing status. + final bool? certificateStatusShouldOverride; + + /// The intent for building manifests. + final SettingsIntent? intent; + + /// Labels of assertions considered "created" by the builder. + final List? createdAssertionLabels; + + /// Whether to prefer box hash for large assets. + final bool? preferBoxHash; + + /// Whether to generate a C2PA archive. + final bool? generateC2paArchive; + + /// Automatic timestamp assertion settings. + final TimeStampSettings? autoTimestampAssertion; + + const BuilderSettingsDefinition({ + this.vendor, + this.claimGeneratorInfo, + this.thumbnail, + this.actions, + this.certificateStatusFetch, + this.certificateStatusShouldOverride, + this.intent, + this.createdAssertionLabels, + this.preferBoxHash, + this.generateC2paArchive, + this.autoTimestampAssertion, + }); + + Map toJson() { + final map = {}; + if (vendor != null) map['vendor'] = vendor; + if (claimGeneratorInfo != null) { + map['claim_generator_info'] = claimGeneratorInfo!.toJson(); + } + if (thumbnail != null) map['thumbnail'] = thumbnail!.toJson(); + if (actions != null) map['actions'] = actions!.toJson(); + if (certificateStatusFetch != null) { + map['certificate_status_fetch'] = certificateStatusFetch!.value; + } + if (certificateStatusShouldOverride != null) { + map['certificate_status_should_override'] = + certificateStatusShouldOverride; + } + if (intent != null) map['intent'] = intent!.toJson(); + if (createdAssertionLabels != null) { + map['created_assertion_labels'] = createdAssertionLabels; + } + if (preferBoxHash != null) map['prefer_box_hash'] = preferBoxHash; + if (generateC2paArchive != null) { + map['generate_c2pa_archive'] = generateC2paArchive; + } + if (autoTimestampAssertion != null) { + map['auto_timestamp_assertion'] = autoTimestampAssertion!.toJson(); + } + return map; + } +} + +// ============================================================================= +// Claim generator info settings +// ============================================================================= + +/// Claim generator information for settings. +@immutable +class ClaimGeneratorInfoSettings { + /// The name of the claim generator. + final String name; + + /// The version of the claim generator. + final String? version; + + /// The operating system the claim generator runs on. + final String? operatingSystem; + + const ClaimGeneratorInfoSettings({ + required this.name, + this.version, + this.operatingSystem, + }); + + Map toJson() { + final map = {'name': name}; + if (version != null) map['version'] = version; + if (operatingSystem != null) map['operating_system'] = operatingSystem; + return map; + } +} + +// ============================================================================= +// Thumbnail settings +// ============================================================================= + +/// Thumbnail generation configuration. +@immutable +class ThumbnailSettings { + /// Whether thumbnail generation is enabled. + final bool? enabled; + + /// Whether to ignore errors during thumbnail generation. + final bool? ignoreErrors; + + /// The long edge dimension in pixels. + final int? longEdge; + + /// The image format for generated thumbnails. + final ThumbnailFormat? format; + + /// Whether to prefer the smallest format. + final bool? preferSmallestFormat; + + /// The quality level for generated thumbnails. + final ThumbnailQuality? quality; + + const ThumbnailSettings({ + this.enabled, + this.ignoreErrors, + this.longEdge, + this.format, + this.preferSmallestFormat, + this.quality, + }); + + Map toJson() { + final map = {}; + if (enabled != null) map['enabled'] = enabled; + if (ignoreErrors != null) map['ignore_errors'] = ignoreErrors; + if (longEdge != null) map['long_edge'] = longEdge; + if (format != null) map['format'] = format!.value; + if (preferSmallestFormat != null) { + map['prefer_smallest_format'] = preferSmallestFormat; + } + if (quality != null) map['quality'] = quality!.value; + return map; + } +} + +/// Thumbnail image format. +enum ThumbnailFormat { + png('png'), + jpeg('jpeg'), + gif('gif'), + webp('webp'), + tiff('tiff'); + + const ThumbnailFormat(this.value); + final String value; +} + +/// Thumbnail quality level. +enum ThumbnailQuality { + low('low'), + medium('medium'), + high('high'); + + const ThumbnailQuality(this.value); + final String value; +} + +// ============================================================================= +// Actions settings +// ============================================================================= + +/// Actions configuration for the builder. +@immutable +class ActionsSettings { + /// Whether all actions are included. + final bool? allActionsIncluded; + + /// Action templates. + final List? templates; + + /// Auto-created action settings. + final AutoActionSettings? autoCreatedAction; + + /// Auto-opened action settings. + final AutoActionSettings? autoOpenedAction; + + /// Auto-placed action settings. + final AutoActionSettings? autoPlacedAction; + + const ActionsSettings({ + this.allActionsIncluded, + this.templates, + this.autoCreatedAction, + this.autoOpenedAction, + this.autoPlacedAction, + }); + + Map toJson() { + final map = {}; + if (allActionsIncluded != null) { + map['all_actions_included'] = allActionsIncluded; + } + if (templates != null) { + map['templates'] = templates!.map((t) => t.toJson()).toList(); + } + if (autoCreatedAction != null) { + map['auto_created_action'] = autoCreatedAction!.toJson(); + } + if (autoOpenedAction != null) { + map['auto_opened_action'] = autoOpenedAction!.toJson(); + } + if (autoPlacedAction != null) { + map['auto_placed_action'] = autoPlacedAction!.toJson(); + } + return map; + } +} + +/// A template for an action assertion. +@immutable +class ActionTemplateSettings { + /// The action identifier. + final String action; + + /// Software agent information for this action. + final ClaimGeneratorInfoSettings? softwareAgent; + + /// Index of the software agent in the claim generator info list. + final int? softwareAgentIndex; + + /// The digital source type URL for this action. + final String? sourceType; + + /// A human-readable description of the action. + final String? description; + + const ActionTemplateSettings({ + required this.action, + this.softwareAgent, + this.softwareAgentIndex, + this.sourceType, + this.description, + }); + + Map toJson() { + final map = {'action': action}; + if (softwareAgent != null) { + map['software_agent'] = softwareAgent!.toJson(); + } + if (softwareAgentIndex != null) { + map['software_agent_index'] = softwareAgentIndex; + } + if (sourceType != null) map['source_type'] = sourceType; + if (description != null) map['description'] = description; + return map; + } +} + +/// Settings for automatic action generation. +@immutable +class AutoActionSettings { + /// Whether the automatic action is enabled. + final bool enabled; + + /// The digital source type URL for the automatic action. + final String? sourceType; + + const AutoActionSettings({required this.enabled, this.sourceType}); + + Map toJson() { + final map = {'enabled': enabled}; + if (sourceType != null) map['source_type'] = sourceType; + return map; + } +} + +// ============================================================================= +// Timestamp settings +// ============================================================================= + +/// Timestamp assertion configuration. +@immutable +class TimeStampSettings { + /// Whether automatic timestamping is enabled. + final bool? enabled; + + /// Whether to skip timestamping if a timestamp already exists. + final bool? skipExisting; + + /// The scope for fetching timestamps. + final TimeStampFetchScope? fetchScope; + + const TimeStampSettings({this.enabled, this.skipExisting, this.fetchScope}); + + Map toJson() { + final map = {}; + if (enabled != null) map['enabled'] = enabled; + if (skipExisting != null) map['skip_existing'] = skipExisting; + if (fetchScope != null) map['fetch_scope'] = fetchScope!.value; + return map; + } +} + +/// Scope for fetching timestamps. +enum TimeStampFetchScope { + parent('parent'), + all('all'); + + const TimeStampFetchScope(this.value); + final String value; +} + +/// Scope for fetching OCSP certificate status. +enum OcspFetchScope { + all('all'), + active('active'); + + const OcspFetchScope(this.value); + final String value; +} + +// ============================================================================= +// Settings intent (sealed) +// ============================================================================= + +/// The intent for building manifests, specified in settings. +/// +/// Encodes as: +/// - `"Edit"` (string) for [SettingsIntent.edit] +/// - `"Update"` (string) for [SettingsIntent.update] +/// - `{"Create": {"digital_source_type": ""}}` for [SettingsIntent.create] +sealed class SettingsIntent { + const SettingsIntent(); + + /// A new digital creation with the specified digital source type URI. + const factory SettingsIntent.create(String digitalSourceType) = + _SettingsIntentCreate; + + /// An edit of a pre-existing parent asset. + static const SettingsIntent edit = _SettingsIntentEdit(); + + /// A restricted version of edit for non-editorial changes. + static const SettingsIntent update = _SettingsIntentUpdate(); + + /// Returns the JSON value for this intent — may be a String ("Edit"/"Update") + /// or a Map (`{"Create": {...}}`). The caller should accept `dynamic`. + dynamic toJson(); +} + +class _SettingsIntentCreate extends SettingsIntent { + final String digitalSourceType; + const _SettingsIntentCreate(this.digitalSourceType); + + @override + Map toJson() => { + 'Create': {'digital_source_type': digitalSourceType}, + }; +} + +class _SettingsIntentEdit extends SettingsIntent { + const _SettingsIntentEdit(); + + @override + String toJson() => 'Edit'; +} + +class _SettingsIntentUpdate extends SettingsIntent { + const _SettingsIntentUpdate(); + + @override + String toJson() => 'Update'; +} + +// ============================================================================= +// Signer settings (sealed) +// ============================================================================= + +/// Signer configuration, either local or remote. +/// +/// Encodes as `{"local": {...}}` or `{"remote": {...}}` depending on variant. +sealed class SignerSettings { + const SignerSettings(); + + /// A local signer with credentials stored on-device. + const factory SignerSettings.local(LocalSignerSettings settings) = + _SignerSettingsLocal; + + /// A remote signer that delegates to a signing service. + const factory SignerSettings.remote(RemoteSignerSettings settings) = + _SignerSettingsRemote; + + Map toJson(); +} + +class _SignerSettingsLocal extends SignerSettings { + final LocalSignerSettings settings; + const _SignerSettingsLocal(this.settings); + + @override + Map toJson() => {'local': settings.toJson()}; +} + +class _SignerSettingsRemote extends SignerSettings { + final RemoteSignerSettings settings; + const _SignerSettingsRemote(this.settings); + + @override + Map toJson() => {'remote': settings.toJson()}; +} + +/// Local signer credentials and configuration. +@immutable +class LocalSignerSettings { + /// The signing algorithm identifier (e.g., `"es256"`). + final String alg; + + /// The certificate chain in PEM format. + final String signCert; + + /// The private key in PEM format. + final String privateKey; + + /// Optional URL of a timestamp authority. + final String? tsaUrl; + + /// Assertion labels referenced by the signer. + final List? referencedAssertions; + + /// Signer roles. + final List? roles; + + const LocalSignerSettings({ + required this.alg, + required this.signCert, + required this.privateKey, + this.tsaUrl, + this.referencedAssertions, + this.roles, + }); + + Map toJson() { + final map = { + 'alg': alg, + 'sign_cert': signCert, + 'private_key': privateKey, + }; + if (tsaUrl != null) map['tsa_url'] = tsaUrl; + if (referencedAssertions != null) { + map['referenced_assertions'] = referencedAssertions; + } + if (roles != null) map['roles'] = roles; + return map; + } +} + +/// Remote signer configuration. +@immutable +class RemoteSignerSettings { + /// The URL of the remote signing service. + final String url; + + /// The signing algorithm identifier. + final String alg; + + /// The certificate chain in PEM format. + final String signCert; + + /// Optional URL of a timestamp authority. + final String? tsaUrl; + + /// Assertion labels referenced by the signer. + final List? referencedAssertions; + + /// Signer roles. + final List? roles; + + const RemoteSignerSettings({ + required this.url, + required this.alg, + required this.signCert, + this.tsaUrl, + this.referencedAssertions, + this.roles, + }); + + Map toJson() { + final map = { + 'url': url, + 'alg': alg, + 'sign_cert': signCert, + }; + if (tsaUrl != null) map['tsa_url'] = tsaUrl; + if (referencedAssertions != null) { + map['referenced_assertions'] = referencedAssertions; + } + if (roles != null) map['roles'] = roles; + return map; + } +} diff --git a/pubspec.yaml b/pubspec.yaml index 29a2398..2a87d2f 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: c2pa_flutter description: "Flutter plugin for C2PA (Coalition for Content Provenance and Authenticity) - read and sign content credentials on mobile devices." -version: 0.0.3 +version: 0.0.4 homepage: https://github.com/nicktardif/c2pa-flutter repository: https://github.com/nicktardif/c2pa-flutter issue_tracker: https://github.com/nicktardif/c2pa-flutter/issues diff --git a/test/c2pa_test.dart b/test/c2pa_test.dart index b7bfeed..47ef547 100644 --- a/test/c2pa_test.dart +++ b/test/c2pa_test.dart @@ -332,7 +332,9 @@ void main() { final call = mockPlatform.methodCalls.last; expect(call.arguments!['manifestJson'], contains('AI Generated Image')); - expect(call.arguments!['manifestJson'], contains('c2pa.ai_generated')); + // AI-generated content uses c2pa.created + trainedAlgorithmicMedia source + // type (spec-compliant); no dedicated action identifier exists. + expect(call.arguments!['manifestJson'], contains('c2pa.created')); expect( call.arguments!['manifestJson'], contains('trainedAlgorithmicMedia'), diff --git a/test/manifest_types_test.dart b/test/manifest_types_test.dart index 4892040..80cab44 100644 --- a/test/manifest_types_test.dart +++ b/test/manifest_types_test.dart @@ -20,7 +20,8 @@ void main() { test('PredefinedAction has correct values', () { expect(PredefinedAction.created.value, 'c2pa.created'); expect(PredefinedAction.edited.value, 'c2pa.edited'); - expect(PredefinedAction.aiGenerated.value, 'c2pa.ai_generated'); + expect(PredefinedAction.watermarkedBound.value, 'c2pa.watermarked.bound'); + expect(PredefinedAction.fontSubset.value, 'font.subset'); }); test('Relationship serializes correctly', () { @@ -269,19 +270,19 @@ void main() { expect(action.changes?.length, 1); }); - test('aiGenerated factory sets correct values', () { - final action = Action.aiGenerated( + test('created action with trainedAlgorithmicMedia source type', () { + // C2PA represents AI-generated content via the trainedAlgorithmicMedia + // digital source type on a created action, not via a custom action string. + final action = Action.created( sourceType: DigitalSourceType.trainedAlgorithmicMedia, softwareAgent: 'AI Model v1', - parameters: {'model': 'test-model'}, ); - expect(action.action, 'c2pa.ai_generated'); + expect(action.action, 'c2pa.created'); expect( action.digitalSourceType, DigitalSourceType.trainedAlgorithmicMedia.url, ); - expect(action.parameters?['model'], 'test-model'); }); test('toJson and fromJson round-trip', () { diff --git a/test/mocks/mock_c2pa_platform.dart b/test/mocks/mock_c2pa_platform.dart index 0ca5b3b..5b3baa7 100644 --- a/test/mocks/mock_c2pa_platform.dart +++ b/test/mocks/mock_c2pa_platform.dart @@ -131,6 +131,26 @@ class MockC2paPlatform extends C2paPlatform with MockPlatformInterfaceMixin { return mockManifestJson ?? _generateMockManifestJson('bytes'); } + /// Remote URL returned by the mock for [getRemoteUrl]; null means embedded manifest. + String? mockRemoteUrl; + + /// Whether the mock reports the manifest as embedded. + bool mockIsManifestEmbedded = true; + + @override + Future getRemoteUrl(String path, {String? mimeType}) async { + _recordCall('getRemoteUrl', {'path': path, 'mimeType': mimeType}); + _checkError(); + return mockRemoteUrl; + } + + @override + Future isManifestEmbedded(String path, {String? mimeType}) async { + _recordCall('isManifestEmbedded', {'path': path, 'mimeType': mimeType}); + _checkError(); + return mockIsManifestEmbedded; + } + // ============================================================================= // Reader API - Enhanced // ============================================================================= @@ -344,6 +364,25 @@ class MockC2paPlatform extends C2paPlatform with MockPlatformInterfaceMixin { ); } + @override + Future builderAddIngredientFromFile( + int handle, + String path, + String? mimeType, + String? ingredientJson, + ) async { + _recordCall('builderAddIngredientFromFile', { + 'handle': handle, + 'path': path, + 'mimeType': mimeType, + 'ingredientJson': ingredientJson, + }); + _checkError(); + builders[handle]?.ingredients.add( + MockIngredient(Uint8List(0), mimeType ?? '', ingredientJson), + ); + } + @override Future builderAddAction(int handle, String actionJson) async { _recordCall('builderAddAction', { @@ -799,6 +838,21 @@ class MockBuilder implements ManifestBuilder { ); } + @override + Future addIngredientFromFile({ + required String path, + String? mimeType, + IngredientConfig? config, + }) async { + _checkDisposed(); + await _platform.builderAddIngredientFromFile( + _handle, + path, + mimeType, + config?.toJson(), + ); + } + @override void addAction(ActionConfig action) { _checkDisposed(); diff --git a/test/settings_definition_test.dart b/test/settings_definition_test.dart new file mode 100644 index 0000000..417ffaa --- /dev/null +++ b/test/settings_definition_test.dart @@ -0,0 +1,240 @@ +/* +This file is licensed to you under the Apache License, Version 2.0 +(http://www.apache.org/licenses/LICENSE-2.0) or the MIT license +(http://opensource.org/licenses/MIT), at your option. + +Unless required by applicable law or agreed to in writing, this software is +distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF +ANY KIND, either express or implied. See the LICENSE-MIT and LICENSE-APACHE +files for the specific language governing permissions and limitations under +each license. +*/ + +import 'dart:convert'; + +import 'package:c2pa_flutter/c2pa.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('C2paSettingsDefinition', () { + test('empty definition serializes to empty object', () { + const def = C2paSettingsDefinition(); + expect(def.toJson(), {}); + expect(def.toJsonString(), '{}'); + }); + + test('version-only definition serializes correctly', () { + const def = C2paSettingsDefinition(version: 1); + expect(def.toJson(), {'version': 1}); + }); + + test('CAWG-keyed fields use snake_case wire names', () { + const def = C2paSettingsDefinition( + version: 1, + cawgTrust: TrustSettings(verifyTrustList: true), + cawgX509Signer: SignerSettings.local( + LocalSignerSettings(alg: 'es256', signCert: 'c', privateKey: 'k'), + ), + ); + final json = def.toJson(); + expect(json.containsKey('cawg_trust'), true); + expect(json.containsKey('cawg_x509_signer'), true); + expect(json.containsKey('cawgTrust'), false); + }); + + test('trust settings serialize snake_case', () { + const trust = TrustSettings( + verifyTrustList: true, + userAnchors: '---user---', + trustAnchors: '---trust---', + trustConfig: '{"foo":"bar"}', + allowedList: 'allowed', + ); + expect(trust.toJson(), { + 'verify_trust_list': true, + 'user_anchors': '---user---', + 'trust_anchors': '---trust---', + 'trust_config': '{"foo":"bar"}', + 'allowed_list': 'allowed', + }); + }); + + test('core settings serialize snake_case', () { + const core = CoreSettings( + merkleTreeChunkSizeInKb: 256, + merkleTreeMaxProofs: 1024, + backingStoreMemoryThresholdInMb: 64, + decodeIdentityAssertions: true, + allowedNetworkHosts: ['timestamp.digicert.com'], + ); + expect(core.toJson(), { + 'merkle_tree_chunk_size_in_kb': 256, + 'merkle_tree_max_proofs': 1024, + 'backing_store_memory_threshold_in_mb': 64, + 'decode_identity_assertions': true, + 'allowed_network_hosts': ['timestamp.digicert.com'], + }); + }); + + test('verify settings include every known flag', () { + const verify = VerifySettings( + verifyAfterReading: true, + verifyAfterSign: false, + verifyTrust: true, + verifyTimestampTrust: false, + ocspFetch: true, + remoteManifestFetch: false, + skipIngredientConflictResolution: true, + strictV1Validation: false, + ); + final json = verify.toJson(); + expect(json['verify_after_reading'], true); + expect(json['verify_after_sign'], false); + expect(json['verify_trust'], true); + expect(json['verify_timestamp_trust'], false); + expect(json['ocsp_fetch'], true); + expect(json['remote_manifest_fetch'], false); + expect(json['skip_ingredient_conflict_resolution'], true); + expect(json['strict_v1_validation'], false); + }); + + test('builder settings encode nested thumbnail and actions', () { + const builder = BuilderSettingsDefinition( + vendor: 'ACME', + claimGeneratorInfo: ClaimGeneratorInfoSettings( + name: 'ACME Editor', + version: '1.0', + operatingSystem: 'iOS 18', + ), + thumbnail: ThumbnailSettings( + enabled: true, + format: ThumbnailFormat.webp, + quality: ThumbnailQuality.high, + longEdge: 512, + ), + actions: ActionsSettings( + allActionsIncluded: true, + autoCreatedAction: AutoActionSettings(enabled: true), + ), + certificateStatusFetch: OcspFetchScope.active, + createdAssertionLabels: ['c2pa.actions'], + preferBoxHash: false, + ); + final json = builder.toJson(); + expect(json['vendor'], 'ACME'); + expect(json['claim_generator_info'], { + 'name': 'ACME Editor', + 'version': '1.0', + 'operating_system': 'iOS 18', + }); + expect(json['thumbnail'], { + 'enabled': true, + 'long_edge': 512, + 'format': 'webp', + 'quality': 'high', + }); + expect(json['actions'], { + 'all_actions_included': true, + 'auto_created_action': {'enabled': true}, + }); + expect(json['certificate_status_fetch'], 'active'); + expect(json['created_assertion_labels'], ['c2pa.actions']); + expect(json['prefer_box_hash'], false); + }); + + test('SettingsIntent.create encodes with digital_source_type', () { + const intent = SettingsIntent.create( + 'http://cv.iptc.org/newscodes/digitalsourcetype/digitalCapture', + ); + expect(intent.toJson(), { + 'Create': { + 'digital_source_type': + 'http://cv.iptc.org/newscodes/digitalsourcetype/digitalCapture', + }, + }); + }); + + test('SettingsIntent.edit and .update encode as strings', () { + expect(SettingsIntent.edit.toJson(), 'Edit'); + expect(SettingsIntent.update.toJson(), 'Update'); + }); + + test('SignerSettings.local encodes under "local"', () { + const signer = SignerSettings.local( + LocalSignerSettings( + alg: 'es256', + signCert: '---CERT---', + privateKey: '---KEY---', + tsaUrl: 'http://timestamp.digicert.com', + referencedAssertions: ['c2pa.actions'], + ), + ); + expect(signer.toJson(), { + 'local': { + 'alg': 'es256', + 'sign_cert': '---CERT---', + 'private_key': '---KEY---', + 'tsa_url': 'http://timestamp.digicert.com', + 'referenced_assertions': ['c2pa.actions'], + }, + }); + }); + + test('SignerSettings.remote encodes under "remote"', () { + const signer = SignerSettings.remote( + RemoteSignerSettings( + url: 'https://signing.example.com/sign', + alg: 'ps256', + signCert: '---CERT---', + ), + ); + expect(signer.toJson(), { + 'remote': { + 'url': 'https://signing.example.com/sign', + 'alg': 'ps256', + 'sign_cert': '---CERT---', + }, + }); + }); + + test('timestamp settings and fetch scope', () { + const ts = TimeStampSettings( + enabled: true, + skipExisting: false, + fetchScope: TimeStampFetchScope.all, + ); + expect(ts.toJson(), { + 'enabled': true, + 'skip_existing': false, + 'fetch_scope': 'all', + }); + }); + + test('full round-trip through JSON string is deterministic', () { + const def = C2paSettingsDefinition( + version: 1, + verify: VerifySettings(verifyTrust: false), + signer: SignerSettings.local( + LocalSignerSettings( + alg: 'es256', + signCert: 'c', + privateKey: 'k', + tsaUrl: 'http://tsa.example', + ), + ), + ); + final serialized = def.toJsonString(); + final parsed = jsonDecode(serialized) as Map; + expect(parsed['version'], 1); + expect(parsed['verify'], {'verify_trust': false}); + expect(parsed['signer'], { + 'local': { + 'alg': 'es256', + 'sign_cert': 'c', + 'private_key': 'k', + 'tsa_url': 'http://tsa.example', + }, + }); + }); + }); +}