Repository Public
1// SP Wallet Core2// File: Sources/SPWalletCore/Domains/Execution/DeveloperCanonical.swift3// Description: The intent the owner's passkey signs to create, rotate or widen an API key (`SPW-APIKEY-INTENT-v1`,4// services/api/src/trading-api/keys.ts `storeIntent`; key-model.ts `canonicalJson` + `intentChallenge`): the challenge5// is SHA-256 of `SPW-APIKEY-INTENT-v1\n<JSON with sorted keys>` — object-bound, never server-random. The USD limits6// of a key are JSON NUMBERS in this contract (the only non-integer numbers of the canonical JSON): they are printed7// the way ECMAScript prints them (ExecutionStableJSON.number).8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import Foundation1213/** Recorded on the key; `nil` = no limit of this kind on the key (the mandate still bounds it). USD, as JSON numbers. */14public struct APIKeyLimits: Codable, Sendable, Equatable {15 public let maxOrderNotionalUsd: ExecutionNullable<Double>16 public let maxDailyNotionalUsd: ExecutionNullable<Double>17 public init(maxOrderNotionalUsd: Double?, maxDailyNotionalUsd: Double?) { self.maxOrderNotionalUsd = .init(maxOrderNotionalUsd); self.maxDailyNotionalUsd = .init(maxDailyNotionalUsd) }18}1920/** An EMPTY list means "not restricted on this axis". */21public struct APIKeyRestrictions: Codable, Sendable, Equatable {22 public let networks: [String]23 public let venues: [String]24 public let instruments: [String]25 /** source addresses allowed to use the key: IPv4/IPv6 addresses or CIDR blocks */26 public let ipAllow: [String]27 public init(networks: [String], venues: [String], instruments: [String], ipAllow: [String]) { self.networks = networks; self.venues = venues; self.instruments = instruments; self.ipAllow = ipAllow }28 /** `cleanRestrictions` of keys.ts: each list without duplicates, sorted. */29 var cleaned: APIKeyRestrictions { .init(networks: APIKeyIntent.uniq(networks), venues: APIKeyIntent.uniq(venues), instruments: APIKeyIntent.uniq(instruments), ipAllow: APIKeyIntent.uniq(ipAllow)) }30}3132/**33 Changes of a key (`KeyChangesSchema`): an absent member is unchanged. `mandate`: `.unchanged`, `.unbind` (JSON null — removes34 authority) or `.bind(id)` (always a widening).35 */36public struct APIKeyChanges: Codable, Sendable, Equatable {37 public enum MandateChange: Sendable, Equatable { case unchanged, unbind, bind(String) }38 public var name: String?39 public var scopes: [String]?40 /** absolute expiry, ISO 8601 */41 public var expiresAt: String?42 public var limits: APIKeyLimits?43 public var restrictions: APIKeyRestrictions?44 public var rateLimitPerMin: Int?45 public var mandate: MandateChange4647 public init(name: String? = nil, scopes: [String]? = nil, expiresAt: String? = nil, limits: APIKeyLimits? = nil, restrictions: APIKeyRestrictions? = nil, rateLimitPerMin: Int? = nil, mandate: MandateChange = .unchanged) {48 self.name = name; self.scopes = scopes; self.expiresAt = expiresAt; self.limits = limits; self.restrictions = restrictions; self.rateLimitPerMin = rateLimitPerMin; self.mandate = mandate49 }50 enum CodingKeys: String, CodingKey { case name, scopes, expiresAt, limits, restrictions, rateLimitPerMin, mandateId }51 public init(from decoder: Decoder) throws {52 let c = try decoder.container(keyedBy: CodingKeys.self)53 name = try c.decodeIfPresent(String.self, forKey: .name); scopes = try c.decodeIfPresent([String].self, forKey: .scopes); expiresAt = try c.decodeIfPresent(String.self, forKey: .expiresAt)54 limits = try c.decodeIfPresent(APIKeyLimits.self, forKey: .limits); restrictions = try c.decodeIfPresent(APIKeyRestrictions.self, forKey: .restrictions); rateLimitPerMin = try c.decodeIfPresent(Int.self, forKey: .rateLimitPerMin)55 if !c.contains(.mandateId) { mandate = .unchanged } else if try c.decodeNil(forKey: .mandateId) { mandate = .unbind } else { mandate = .bind(try c.decode(String.self, forKey: .mandateId)) }56 }57 public func encode(to encoder: Encoder) throws {58 var c = encoder.container(keyedBy: CodingKeys.self)59 try c.encodeIfPresent(name, forKey: .name); try c.encodeIfPresent(scopes, forKey: .scopes); try c.encodeIfPresent(expiresAt, forKey: .expiresAt)60 try c.encodeIfPresent(limits, forKey: .limits); try c.encodeIfPresent(restrictions, forKey: .restrictions); try c.encodeIfPresent(rateLimitPerMin, forKey: .rateLimitPerMin)61 switch mandate { case .unchanged: break; case .unbind: try c.encodeNil(forKey: .mandateId); case .bind(let id): try c.encode(id, forKey: .mandateId) }62 }63 /** `checkedChanges` of keys.ts: the form the server stores in the intent (scopes and restriction lists without duplicates, sorted; name trimmed). */64 var normalized: APIKeyChanges {65 var n = self66 n.name = name?.trimmingCharacters(in: .whitespacesAndNewlines); n.scopes = scopes.map(APIKeyIntent.uniq); n.restrictions = restrictions?.cleaned67 return n68 }69 public var isEmpty: Bool { self == APIKeyChanges() }70}7172/** `SPW-APIKEY-INTENT-v1`. One of three actions; the members of the two others are absent. */73public struct APIKeyIntent: Codable, Sendable, Equatable, PasskeyApprovable {74 public static let domain = "SPW-APIKEY-INTENT-v1"75 /** The key a `create` will insert: its PUBLIC id, its scopes (permissions), limits, restrictions, expiry and mandate binding. */76 public struct Key: Codable, Sendable, Equatable {77 public let id: String78 public let name: String79 public let scopes: [String]80 /** ISO 8601 */81 public let expiresAt: String82 public let limits: APIKeyLimits83 public let restrictions: APIKeyRestrictions84 public let rateLimitPerMin: Int85 public let mandateId: ExecutionNullable<String>86 }87 public let v: Int88 /** `create`, `rotate`, `update` */89 public let action: String90 public let intentId: String91 /** the wallet origin the intent was prepared for */92 public let origin: String93 /** ISO 8601 */94 public let preparedAt: String95 public let key: Key?96 public let keyId: String?97 public let newKeyId: String?98 public let changes: APIKeyChanges?99 /** update: the changes that give the key MORE authority */100 public let widening: [String]?101102 public init(served: JSONValue?) throws {103 self = try ExecutionStrict.decode(APIKeyIntent.self, from: served, path: "intent")104 guard v == 1 else { throw ApprovalError.unsupported("API key intent version \(v)") }105 let shape: Bool106 switch action {107 case "create": shape = key != nil && keyId == nil && newKeyId == nil && changes == nil && widening == nil108 case "rotate": shape = key == nil && keyId != nil && newKeyId != nil && changes == nil && widening == nil109 case "update": shape = key == nil && keyId != nil && newKeyId == nil && changes != nil && widening != nil110 default: throw ApprovalError.unsupported("API key intent action \(action)")111 }112 guard shape else { throw ApprovalError.unsupported("API key intent of action \(action) with the members of another action") }113 for id in [key?.id, keyId, newKeyId].compactMap({ $0 }) { guard ExecutionPattern.matches(id, "spk_[0-9a-f]{12}") else { throw ApprovalError.unsupported("API key id") } }114 }115 public func canonicalBytes() throws -> Data { try ExecutionStableJSON.bytes(domain: Self.domain, try JSONValue.from(self)) }116117 /** `[...new Set(a)].sort()` */118 static func uniq(_ a: [String]) -> [String] { Array(Set(a)).sorted(by: executionCodeUnitOrder) }119}120