|
| 1 | +// SPDX-License-Identifier: Apache-2.0 |
| 2 | +// Original versioned, digest-checked envelope over RFC 8785 canonical JSON. |
| 3 | +import Foundation |
| 4 | + |
| 5 | +/// A versioned, self-checking record of one JSON payload, written as RFC 8785 canonical JSON. |
| 6 | +/// |
| 7 | +/// An envelope names what its payload is (``type``) and which schema version of |
| 8 | +/// that type it follows (``version``), so a store can migrate old records. Its |
| 9 | +/// wire form is one canonical object with six members: |
| 10 | +/// |
| 11 | +/// ```json |
| 12 | +/// {"digest":"sha256:…","format":"swift-json-envelope","formatVersion":1,"payload":{…},"type":"mcp.task","version":3} |
| 13 | +/// ``` |
| 14 | +/// |
| 15 | +/// `digest` is the SHA-256 of the payload's canonical bytes. Decoding recomputes |
| 16 | +/// it, so a damaged payload is detected, and equal payloads always have equal |
| 17 | +/// digests, so the digest can serve as a content address. Because the whole |
| 18 | +/// envelope is canonical, equal envelopes encode to equal bytes. |
| 19 | +/// |
| 20 | +/// Format version 1 is fixed: the member names, the marker and the digest |
| 21 | +/// algorithm do not change. A later format would use a new `formatVersion`. |
| 22 | +public struct JSONEnvelope: Sendable, Equatable { |
| 23 | + /// The format marker, `swift-json-envelope`. |
| 24 | + public static let format = "swift-json-envelope" |
| 25 | + /// The format version this type reads and writes, `1`. |
| 26 | + public static let formatVersion = 1 |
| 27 | + /// The largest accepted ``type`` length in UTF-8 bytes. |
| 28 | + public static let maximumTypeBytes = 256 |
| 29 | + /// The accepted ``version`` range: the positive integers that binary64 represents exactly. |
| 30 | + public static let versions: ClosedRange<Int> = 1...9_007_199_254_740_991 |
| 31 | + |
| 32 | + /// The caller's name for the kind of payload, such as `mcp.task`. |
| 33 | + public let type: String |
| 34 | + /// The schema version of ``type`` that the payload follows. |
| 35 | + public let version: Int |
| 36 | + /// The enveloped value. |
| 37 | + public let payload: JSON |
| 38 | + |
| 39 | + /// Creates an envelope after checking its type and version. |
| 40 | + /// |
| 41 | + /// - Throws: ``JSONEnvelopeFailure/invalidType`` for an empty type or one longer |
| 42 | + /// than ``maximumTypeBytes``; ``JSONEnvelopeFailure/invalidVersion`` for a version |
| 43 | + /// outside ``versions``. |
| 44 | + /// |
| 45 | + /// - Parameters: |
| 46 | + /// - type: A non-empty name for the kind of payload, at most 256 UTF-8 bytes. |
| 47 | + /// - version: The payload's schema version, from 1 through 2^53 − 1. |
| 48 | + /// - payload: The value to envelope. |
| 49 | + public init(type: String, version: Int, payload: JSON) throws { |
| 50 | + guard !type.isEmpty, type.utf8.count <= Self.maximumTypeBytes else { throw JSONEnvelopeFailure.invalidType } |
| 51 | + guard Self.versions.contains(version) else { throw JSONEnvelopeFailure.invalidVersion } |
| 52 | + self.type = type; self.version = version; self.payload = payload |
| 53 | + } |
| 54 | + |
| 55 | + /// Writes the envelope's canonical bytes and returns them with the payload digest. |
| 56 | + /// |
| 57 | + /// - Returns: The canonical envelope bytes and the `sha256:` digest of the payload. |
| 58 | + /// - Throws: Inexact conversion for a number the policy refuses, resource failure or cancellation. |
| 59 | + /// |
| 60 | + /// - Parameters: |
| 61 | + /// - options: Limits and the canonical number policy. |
| 62 | + public func encode(options: JSONEnvelopeOptions = .init()) throws -> JSONEnvelopeEncoding { |
| 63 | + try encodeWithReport(options: options).result |
| 64 | + } |
| 65 | + /// Writes the envelope with one cumulative work ledger. |
| 66 | + /// |
| 67 | + /// - Returns: The encoding and the ledger's charged counts. |
| 68 | + /// - Throws: Inexact conversion for a number the policy refuses, resource failure or cancellation. |
| 69 | + /// |
| 70 | + /// - Parameters: |
| 71 | + /// - options: Limits and the canonical number policy. |
| 72 | + public func encodeWithReport(options: JSONEnvelopeOptions = .init()) throws -> JSONOperationReport<JSONEnvelopeEncoding> { |
| 73 | + var meter = try JSONWorkMeter(limits: options.limits, domain: .writing) |
| 74 | + let writer = JSONCanonicalWriter(limits: options.limits, numberPolicy: options.numberPolicy) |
| 75 | + let payloadBytes = try writer.write(payload, meter: &meter) |
| 76 | + let digest = try Self.digest(of: payloadBytes, meter: &meter) |
| 77 | + try meter.resetValueBounds(); let typeBytes = try writer.write(.string(type), meter: &meter) |
| 78 | + try meter.resetValueBounds(); let versionBytes = try writer.write(.number(JSONNumber(integer: version)), meter: &meter) |
| 79 | + // Members in RFC 8785 order; every name is ASCII, so UTF-16 order is byte order. |
| 80 | + var bytes: [UInt8] = [] |
| 81 | + func append<C: Collection>(_ part: C, meter: inout JSONWorkMeter) throws where C.Element == UInt8 { |
| 82 | + for byte in part { try meter.work(); try meter.retain(1); bytes.append(byte) } |
| 83 | + } |
| 84 | + func literal(_ text: String, meter: inout JSONWorkMeter) throws { |
| 85 | + try meter.charge(.outputBytes, UInt64(text.utf8.count)); try append(text.utf8, meter: &meter) |
| 86 | + } |
| 87 | + try literal("{\"digest\":\"\(digest)\",\"format\":\"\(Self.format)\",\"formatVersion\":\(Self.formatVersion),\"payload\":", meter: &meter) |
| 88 | + try append(payloadBytes, meter: &meter) |
| 89 | + try literal(",\"type\":", meter: &meter); try append(typeBytes, meter: &meter) |
| 90 | + try literal(",\"version\":", meter: &meter); try append(versionBytes, meter: &meter) |
| 91 | + try literal("}", meter: &meter) |
| 92 | + try meter.checkpoint() |
| 93 | + return .init(result: .init(data: Data(bytes), digest: digest), statistics: meter.statistics()) |
| 94 | + } |
| 95 | + |
| 96 | + /// Reads an envelope and verifies its format, fields and payload digest. |
| 97 | + /// |
| 98 | + /// The input may be any strict JSON spelling of the envelope object; canonical |
| 99 | + /// bytes are not required. Use the same number policy that encoded it. |
| 100 | + /// |
| 101 | + /// - Returns: The checked envelope. |
| 102 | + /// - Throws: ``JSONEnvelopeFailure`` for a well-formed JSON value that is not a |
| 103 | + /// valid version 1 envelope or whose digest does not match; `JSONFailure` for |
| 104 | + /// syntax, a refused number, resource failure; or cancellation. |
| 105 | + /// |
| 106 | + /// - Parameters: |
| 107 | + /// - data: The envelope bytes. |
| 108 | + /// - options: Limits and the canonical number policy used for the digest. |
| 109 | + public static func decode(_ data: Data, options: JSONEnvelopeOptions = .init()) throws -> JSONEnvelope { |
| 110 | + try decodeWithReport(data, options: options).result |
| 111 | + } |
| 112 | + /// Reads and verifies an envelope with one cumulative work ledger. |
| 113 | + /// |
| 114 | + /// See ``decode(_:options:)``. |
| 115 | + /// |
| 116 | + /// - Returns: The checked envelope and the ledger's charged counts. |
| 117 | + /// - Throws: ``JSONEnvelopeFailure``, `JSONFailure` or cancellation, as for ``decode(_:options:)``. |
| 118 | + /// |
| 119 | + /// - Parameters: |
| 120 | + /// - data: The envelope bytes. |
| 121 | + /// - options: Limits and the canonical number policy used for the digest. |
| 122 | + public static func decodeWithReport(_ data: Data, options: JSONEnvelopeOptions = .init()) throws -> JSONOperationReport<JSONEnvelope> { |
| 123 | + var meter = try JSONWorkMeter(limits: options.limits, domain: .core) |
| 124 | + try meter.require(.inputBytes, UInt64(data.count)) |
| 125 | + var input: [UInt8] = [] |
| 126 | + for byte in data { try meter.work(); try meter.retain(1); input.append(byte) } |
| 127 | + let root = try JSONParser().parse(input, meter: &meter) |
| 128 | + try meter.release(UInt64(input.count)); input = [] |
| 129 | + |
| 130 | + guard case .object(let object) = root, object.count == 6 else { throw JSONEnvelopeFailure.invalidFormat } |
| 131 | + func member(_ name: String, meter: inout JSONWorkMeter) throws -> JSON { |
| 132 | + guard let value = try object.lookup(name, meter: &meter) else { throw JSONEnvelopeFailure.invalidFormat } |
| 133 | + return value |
| 134 | + } |
| 135 | + guard case .string(format) = try member("format", meter: &meter) else { throw JSONEnvelopeFailure.invalidFormat } |
| 136 | + guard case .number(let formatVersion) = try member("formatVersion", meter: &meter) else { throw JSONEnvelopeFailure.invalidFormat } |
| 137 | + guard try integer(formatVersion, meter: &meter) == Self.formatVersion else { |
| 138 | + throw JSONEnvelopeFailure.unsupportedFormatVersion |
| 139 | + } |
| 140 | + guard case .string(let type) = try member("type", meter: &meter) else { throw JSONEnvelopeFailure.invalidType } |
| 141 | + guard case .number(let versionNumber) = try member("version", meter: &meter), |
| 142 | + let version = try integer(versionNumber, meter: &meter) else { throw JSONEnvelopeFailure.invalidVersion } |
| 143 | + guard case .string(let digest) = try member("digest", meter: &meter), isDigest(digest) else { throw JSONEnvelopeFailure.invalidDigest } |
| 144 | + let payload = try member("payload", meter: &meter) |
| 145 | + let envelope = try JSONEnvelope(type: type, version: version, payload: payload) |
| 146 | + |
| 147 | + try meter.resetValueBounds() |
| 148 | + let writer = JSONCanonicalWriter(limits: options.limits, numberPolicy: options.numberPolicy) |
| 149 | + let payloadBytes = try writer.write(payload, meter: &meter) |
| 150 | + guard try Self.digest(of: payloadBytes, meter: &meter) == digest else { throw JSONEnvelopeFailure.digestMismatch } |
| 151 | + try meter.checkpoint() |
| 152 | + return .init(result: envelope, statistics: meter.statistics()) |
| 153 | + } |
| 154 | + |
| 155 | + /// The integer value, or nil when the number is not an integer that fits `Int`. |
| 156 | + private static func integer(_ number: JSONNumber, meter: inout JSONWorkMeter) throws -> Int? { |
| 157 | + do { return try number.integer(as: Int.self, meter: &meter) } |
| 158 | + catch let failure as JSONFailure where failure.category == .conversion { return nil } |
| 159 | + } |
| 160 | + private static func digest(of bytes: [UInt8], meter: inout JSONWorkMeter) throws -> String { |
| 161 | + "sha256:" + (try JSONSHA256Core.hexadecimal(bytes, accounting: &meter)) |
| 162 | + } |
| 163 | + private static func isDigest(_ text: String) -> Bool { |
| 164 | + let bytes = Array(text.utf8) |
| 165 | + guard bytes.count == 71, bytes.starts(with: Array("sha256:".utf8)) else { return false } |
| 166 | + return bytes.dropFirst(7).allSatisfy { (0x30...0x39).contains($0) || (0x61...0x66).contains($0) } |
| 167 | + } |
| 168 | +} |
| 169 | + |
| 170 | +/// Limits and the number policy for encoding and decoding a ``JSONEnvelope``. |
| 171 | +public struct JSONEnvelopeOptions: Sendable { |
| 172 | + /// Finite capacities and work quotas applied to each call. |
| 173 | + public var limits: JSONLimits |
| 174 | + /// The canonical number policy for the payload; decoding must use the policy that encoded it. |
| 175 | + public var numberPolicy: JSONCanonicalWriter.NumberPolicy |
| 176 | + /// Creates the configuration; finite limits are checked when an operation begins. |
| 177 | + /// |
| 178 | + /// - Parameters: |
| 179 | + /// - limits: Finite inclusive capacities and work quotas for each call. |
| 180 | + /// - numberPolicy: Refuse (the default) or round numbers that binary64 cannot represent exactly. |
| 181 | + public init(limits: JSONLimits = .balanced, numberPolicy: JSONCanonicalWriter.NumberPolicy = .preserving) { |
| 182 | + self.limits = limits; self.numberPolicy = numberPolicy |
| 183 | + } |
| 184 | +} |
| 185 | + |
| 186 | +/// The canonical bytes of a ``JSONEnvelope`` and the digest of its payload. |
| 187 | +public struct JSONEnvelopeEncoding: Sendable, Equatable { |
| 188 | + /// The canonical envelope bytes. |
| 189 | + public let data: Data |
| 190 | + /// The payload digest, `sha256:` followed by 64 lowercase hexadecimal digits. |
| 191 | + public let digest: String |
| 192 | +} |
| 193 | + |
| 194 | +/// Why a well-formed JSON value is not a valid version 1 ``JSONEnvelope``. |
| 195 | +/// |
| 196 | +/// Syntax, resource and number-conversion failures are reported as `JSONFailure`. |
| 197 | +/// No case carries input text. |
| 198 | +public enum JSONEnvelopeFailure: Error, Sendable, Equatable { |
| 199 | + /// The root is not an object with exactly the six envelope members, or the format marker is wrong. |
| 200 | + case invalidFormat |
| 201 | + /// The format version is not 1. |
| 202 | + case unsupportedFormatVersion |
| 203 | + /// The type is not a non-empty string of at most 256 UTF-8 bytes. |
| 204 | + case invalidType |
| 205 | + /// The version is not an integer from 1 through 2^53 − 1. |
| 206 | + case invalidVersion |
| 207 | + /// The digest is not `sha256:` followed by 64 lowercase hexadecimal digits. |
| 208 | + case invalidDigest |
| 209 | + /// The payload's canonical digest differs from the recorded digest. |
| 210 | + case digestMismatch |
| 211 | +} |
0 commit comments