SPB Git

Repository Public

RiskAPI.swift 12.6 KB 208 lines swift

1// SP Wallet Core2// File: Sources/SPWalletCore/Domains/Execution/RiskAPI.swift3// Description: The owner's routes of the risk engine (/api/v1/risk, services/api/src/orders/index.ts `executionRoutes`).4//              The server's rule, kept as it is: what REMOVES authority is free (engaging a switch, tightening a limit, switching an5//              automatic stop on); what GIVES authority back needs the passkey over an intent (releasing a switch, loosening a6//              limit, switching an automatic stop off). Every such intent is recomputed here, compared with what was asked and7//              displayed, and only then handed to the passkey. No challenge of these routes is server-random.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import Foundation1213/** A verified loosening of the limits: the whole new set as it will be written, and the fields the server found loosened. */14public struct RiskLimitsApproval: Sendable {15    public let approval: VerifiedApproval<RiskLimitsIntent>16    public var intent: RiskLimitsIntent { approval.object }17    public var mode: RiskMode { intent.mode }18    public var limits: EngineRiskLimits { intent.limits }19    public var loosened: [String] { intent.loosened }20}21public enum RiskLimitsPreparation: Sendable {22    /** nothing is loosened: `setLimits` applies the change with the session alone */23    case passkeyNotNeeded24    case approval(RiskLimitsApproval)25}2627/** A verified release of one switch, naming the engagement the owner was shown. */28public struct RiskSwitchReleaseApproval: Sendable {29    public let approval: VerifiedApproval<RiskSwitchReleaseIntent>30    public var intent: RiskSwitchReleaseIntent { approval.object }31    public var kind: RiskSwitchKind { intent.kind }32}33public enum RiskSwitchReleasePreparation: Sendable {34    /** the switch is not engaged: there is nothing to release */35    case notEngaged36    case approval(RiskSwitchReleaseApproval)37}3839public struct AutoKillApproval: Sendable {40    public let approval: VerifiedApproval<AutoKillIntent>41    public var intent: AutoKillIntent { approval.object }42    public var auto: AutoKillSettings { intent.auto }43    public var loosened: [String] { intent.loosened }44}45public enum AutoKillPreparation: Sendable {46    case passkeyNotNeeded47    case approval(AutoKillApproval)48}4950public struct RiskAPI: Sendable {51    let client: APIClient52    public init(_ client: APIClient) { self.client = client }5354    private struct Prepared: Decodable, Sendable {55        let needed: Bool56        let kind: String?57        let loosened: [String]?58        let intent: JSONValue?59        let hash: String?60        let options: PasskeyRequestOptions?61        let expiresAt: Int?62    }63    private struct AssertionBody: Encodable, Sendable { let assertion: PasskeyAssertion }6465    // MARK: reads6667    public func state() async throws -> RiskState { try await client.get("/risk/state") }6869    /** The log of the risk engine, newest first (1…200 rows). */70    public func decisions(limit: Int = 50) async throws -> [RiskDecision] {71        struct R: Decodable, Sendable { let decisions: [RiskDecision] }72        return try await client.get("/risk/decisions", query: ["limit": String(min(max(limit, 1), 200))], as: R.self).decisions73    }7475    public func exposure(book: RiskBook) async throws -> RiskExposure { try await client.get("/risk/exposure", query: ["book": book.rawValue]) }7677    public func limits(mode: RiskMode) async throws -> RiskLimitsView { try await client.get("/risk/limits/\(mode.rawValue)") }7879    // MARK: switches8081    /**82     Engage the global kill switch: no passkey, effective at once, for every principal. Throws when the answer does not show83     the switch ON — the caller must never assume it.84     */85    public func engageKillSwitch(reason: String) async throws -> RiskSwitches { try await engage(.killSwitch, reason: reason) }8687    /** Engage read-only mode (only cancels pass): no passkey. */88    public func engageReadOnly(reason: String) async throws -> RiskSwitches { try await engage(.readOnly, reason: reason) }8990    private func engage(_ kind: RiskSwitchKind, reason: String) async throws -> RiskSwitches {91        struct Body: Encodable, Sendable { let reason: String }92        let s: RiskSwitches = try await client.post("/risk/\(kind.route)", body: Body(reason: String(reason.trimmingCharacters(in: .whitespacesAndNewlines).prefix(200))))93        guard s.state(of: kind).on else { throw APIError(status: 200, code: "switch_not_confirmed", message: "the server did not confirm that the switch is engaged") }94        return s95    }9697    /**98     Step 1 of a release. `displayed` is the switch as the owner sees it on screen: the intent must release THAT engagement99     (same instant, same actor, same reason) — a switch re-engaged since is another one, and is refused here before the passkey.100     */101    public func prepareRelease(_ kind: RiskSwitchKind, displayed: RiskSwitch, now: Date = Date()) async throws -> RiskSwitchReleasePreparation {102        let p: Prepared = try await client.post("/risk/\(kind.route)/release/prepare")103        guard p.needed else { return .notEngaged }104        let intent = try RiskSwitchReleaseIntent(served: p.intent)105        guard intent.kind == kind, p.kind == kind.rawValue else { throw ApprovalError.inconsistent("the intent releases another switch") }106        guard displayed.on else { throw ApprovalError.inconsistent("the switch shown is not engaged") }107        guard intent.engagedAt == displayed.at else { throw ApprovalError.inconsistent("the switch was engaged at another time than the one shown") }108        guard intent.engagedBy == displayed.by?.label else { throw ApprovalError.inconsistent("the switch was engaged by another actor than the one shown") }109        guard intent.reason == displayed.reason else { throw ApprovalError.inconsistent("the reason of the switch is not the one shown") }110        guard let options = p.options else { throw ApprovalError.unsupported("no passkey request in the answer") }111        try Self.checkStamp(intent, statedExpiry: p.expiresAt, statedHash: p.hash, now: now)112        return .approval(RiskSwitchReleaseApproval(approval: try ApprovalBinding.verify(intent, options: options, rpId: client.configuration.rpId)))113    }114115    /** Step 2: the passkey signs the verified challenge; the server releases the switch only on that assertion. */116    public func release(_ a: RiskSwitchReleaseApproval, with authenticator: PasskeyAuthenticator, now: Date = Date()) async throws -> RiskSwitches {117        try a.intent.requireCurrent(now)118        return try await submitRelease(a.kind, assertion: try await authenticator.assert(a.approval.options, rpId: client.configuration.rpId))119    }120    /** Second half of `release`, separate so that a lost answer is followed by a read of the state instead of a second signature. */121    public func submitRelease(_ kind: RiskSwitchKind, assertion: PasskeyAssertion) async throws -> RiskSwitches {122        try await client.post("/risk/\(kind.route)/release", body: AssertionBody(assertion: assertion))123    }124125    // MARK: limits126127    private struct LimitsBody: Encodable, Sendable { let limits: EngineRiskLimits }128129    /**130     Replace the limit set of a mode WITHOUT a passkey. The server accepts it only when nothing is loosened; otherwise it answers131     403 `passkey_required` naming the loosened fields (use `prepareLimits`). The set REPLACES the stored one.132     */133    public func setLimits(mode: RiskMode, limits: EngineRiskLimits) async throws -> RiskLimitsView {134        try limits.validate()135        return try await client.post("/risk/limits/\(mode.rawValue)", body: LimitsBody(limits: limits))136    }137138    /**139     Step 1 of a change that loosens something: the server stores ONE intent for the mode and answers it with the passkey request.140     Verified here: the intent carries exactly the limits asked (every value), for the mode asked; the loosened list is the one stated.141     */142    public func prepareLimits(mode: RiskMode, limits: EngineRiskLimits, now: Date = Date()) async throws -> RiskLimitsPreparation {143        try limits.validate()144        let p: Prepared = try await client.post("/risk/limits/\(mode.rawValue)/prepare", body: LimitsBody(limits: limits))145        guard p.needed else { return .passkeyNotNeeded }146        let intent = try RiskLimitsIntent(served: p.intent)147        guard intent.mode == mode else { throw ApprovalError.inconsistent("the intent changes the limits of another mode") }148        guard intent.limits == limits else { throw ApprovalError.inconsistent("the limits to approve are not the limits requested (\(Self.firstDifference(intent.limits, limits)))") }149        guard !intent.loosened.isEmpty, intent.loosened == (p.loosened ?? []) else { throw ApprovalError.inconsistent("the loosened fields of the intent are not the ones stated") }150        guard let options = p.options else { throw ApprovalError.unsupported("no passkey request in the answer") }151        try Self.checkStamp(intent, statedExpiry: p.expiresAt, statedHash: p.hash, now: now)152        return .approval(RiskLimitsApproval(approval: try ApprovalBinding.verify(intent, options: options, rpId: client.configuration.rpId)))153    }154155    public func approveLimits(_ a: RiskLimitsApproval, with authenticator: PasskeyAuthenticator, now: Date = Date()) async throws -> RiskLimitsView {156        try a.intent.requireCurrent(now)157        return try await submitLimits(mode: a.mode, assertion: try await authenticator.assert(a.approval.options, rpId: client.configuration.rpId))158    }159    public func submitLimits(mode: RiskMode, assertion: PasskeyAssertion) async throws -> RiskLimitsView {160        try await client.post("/risk/limits/\(mode.rawValue)/approve", body: AssertionBody(assertion: assertion))161    }162163    // MARK: automatic stops164165    private struct AutoAnswer: Decodable, Sendable { let auto: AutoKillSettings }166167    /** Change the automatic stops WITHOUT a passkey: accepted only when none is switched off (otherwise 403 `passkey_required`). */168    public func setAutoKill(_ auto: AutoKillSettings) async throws -> AutoKillSettings {169        struct Body: Encodable, Sendable { let auto: AutoKillSettings }170        return try await client.post("/risk/auto", body: Body(auto: auto), as: AutoAnswer.self).auto171    }172173    public func prepareAutoKill(_ auto: AutoKillSettings, now: Date = Date()) async throws -> AutoKillPreparation {174        struct Body: Encodable, Sendable { let auto: AutoKillSettings }175        let p: Prepared = try await client.post("/risk/auto/prepare", body: Body(auto: auto))176        guard p.needed else { return .passkeyNotNeeded }177        let intent = try AutoKillIntent(served: p.intent)178        guard intent.auto == auto else { throw ApprovalError.inconsistent("the automatic stops to approve are not the ones requested") }179        guard !intent.loosened.isEmpty, intent.loosened == (p.loosened ?? []) else { throw ApprovalError.inconsistent("the loosened fields of the intent are not the ones stated") }180        guard let options = p.options else { throw ApprovalError.unsupported("no passkey request in the answer") }181        try Self.checkStamp(intent, statedExpiry: p.expiresAt, statedHash: p.hash, now: now)182        return .approval(AutoKillApproval(approval: try ApprovalBinding.verify(intent, options: options, rpId: client.configuration.rpId)))183    }184185    public func approveAutoKill(_ a: AutoKillApproval, with authenticator: PasskeyAuthenticator, now: Date = Date()) async throws -> AutoKillSettings {186        try a.intent.requireCurrent(now)187        return try await submitAutoKill(a.auto, assertion: try await authenticator.assert(a.approval.options, rpId: client.configuration.rpId))188    }189    public func submitAutoKill(_ auto: AutoKillSettings, assertion: PasskeyAssertion) async throws -> AutoKillSettings {190        struct Body: Encodable, Sendable { let auto: AutoKillSettings; let assertion: PasskeyAssertion }191        return try await client.post("/risk/auto", body: Body(auto: auto, assertion: assertion), as: AutoAnswer.self).auto192    }193194    // MARK: checks195196    static func checkStamp<I: ExecutionStampedIntent>(_ intent: I, statedExpiry: Int?, statedHash: String?, now: Date) throws {197        guard intent.createdAt <= intent.expiresAt, statedExpiry == intent.expiresAt else { throw ApprovalError.inconsistent("the approval window stated is not the intent's") }198        try intent.requireCurrent(now)199        try ApprovalBinding.requireStatedHash(statedHash, of: intent, what: "intent")200    }201202    /** The first limit whose value differs, by name (for the refusal message). */203    static func firstDifference(_ a: EngineRiskLimits, _ b: EngineRiskLimits) -> String {204        let x = (try? JSONValue.from(a))?.objectValue ?? [:], y = (try? JSONValue.from(b))?.objectValue ?? [:]205        return Set(x.keys).union(y.keys).sorted().first { x[$0] != y[$0] } ?? "limits"206    }207}208
Files main
Menu

Theme